Ankit
Ankit

Reputation: 2256

CrudRepository in Spring JPA Repository

I was trying to understand use of JPA Repository in Spring Boot.

I was able to execute the list operation with following DAO

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

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

Since, CountryEntity have primary key as char. I was confused about use of Long in DAO class

Thanks

Upvotes: 4

Views: 4066

Answers (1)

Nico Van Belle
Nico Van Belle

Reputation: 5166

The Repository interface in spring-data takes two generic type parameters; the domain class to manage as well as the id type of the domain class.

So the second type parameter represents the type of the primary key.

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);      
}

When you call a function that does not use the id of the entity, no type matching will be done and you will not run into issues. Such as in your case.

On the other hand, you will run into issues when using the operations that use the id like findOne(ID), exists(ID), delete(ID) and findAll(Iterable<ID>).

For more information on Repositories, check the documentation here.

Upvotes: 5

Related Questions