I am working on a Spring Boot application that uses Spring Data JPA (on Hibernate 4) to access to my DB.
My doubt is related on the DAO interfaces (used by JPA to automatically generate the queries).
So, in my project I have these 2 interfaces:
1) AccomodationDAO:
@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface AccomodationDAO extends JpaRepository<Accomodation, Long> {
Accomodation findById(@Param("id") Long id);
}
2) EventDAO:
public interface EventDAO extends CrudRepository<Event, Integer> {
public Event findByLocation(Point location);
public Event findById(@Param("id") Integer id);
}
They both works fine and use the same logic to declare queryes.
My only doubt is: the first one extends JpaRepository while the second one implements CrudRepository.
What exactly is the difference between JpaRepository and CrudRepository? What is the best choise to use or in what case is better use one instead the other choice?
Another doubt is: why my defined DAO interfaces extends JpaRepository and CrudRepository that are themselves interfaces? From what I know the interfaces are implemented and not extended...what am I missing?
Each of these defines its own functionality: CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
Here in the following image Repository, CrudRepository and PagingAndSortingRepository belong to Spring Data Commons whereas JpaRepository belongs to Spring Data JPA. It is a base interface and extends Repository Interface. It extends PagingAndSortingRepository that extends CrudRepository.
Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
Their main functions are: CrudRepository mainly provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sorting records. JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.
Note that JpaRepository extends CrudRepository. Compare the JavaDoc of these two interfaces:
JpaRepository vs CrudRepository
In short JpaRepository
List
's instead of Iterable
'sIf you are using JPA you should use JpaRepository.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With