Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 521
Ankit Avatar asked Nov 02 '25 07:11

Ankit


1 Answers

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.

like image 54
Nico Van Belle Avatar answered Nov 03 '25 21:11

Nico Van Belle