Spring JPA Repository 中的 CrudRepository

3

我正在尝试理解Spring Boot中JPA Repository的使用。

以下是我使用DAO执行列表操作的代码:

@Repository
public interface CountryManipulationDAO extends CrudRepository<CountryEntity, Long>{

    @Query("Select a from CountryEntity a")
    public List<CountryEntity> listCountries();

由于 CountryEntity 的主键是 char 类型,我对 DAO 类中使用 Long 感到困惑。

谢谢。


1
将CrudRepository<CountryEntity, Long>更改为CrudRepository<CountryEntity, Character>。CrudRepository模板中的第二个参数是指id的类型。 - Afridi
我想知道Long的用途。将其更改为Character不会扩展我的知识。 - Ankit
1
当您使用诸如findOne(ID)exists(ID)delete(ID)等使用ID的通用类型的操作时,最有可能遇到问题。 - Nico Van Belle
谢谢@NicoVanBelle,这意味着Long代表DTO的主键? - Ankit
@Ankit 正确。请检查接口:Interface CrudRepository<T,ID extends Serializable> - Nico Van Belle
当您扩展CrudRepository或任何其他预定义的Spring Data存储库接口时,不需要使用@Repository注解。 - Jens Schauder
1个回答

4

Repository接口在spring-data中有两个泛型类型参数;一个是要管理的领域类,另一个是领域类的id类型。

因此,第二个类型参数代表主键的类型。

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
    <S extends T> S save(S entity);
    T findOne(ID primaryKey);
    Iterable<T> findAll();
    Long count();
    void delete(T entity);                                                                                                 
    boolean exists(ID primaryKey);      
}

当您调用一个不使用实体的id的函数时,不会进行类型匹配,并且不会遇到问题。就像在您的情况下。

另一方面,当使用使用id的操作,例如findOne(ID)exists(ID)delete(ID)findAll(Iterable<ID>)时,您将遇到问题。

有关repositories的更多信息,请查阅此处的文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接