AndreaNobili AndreaNobili - 1 year ago 233
Java Question

What exactly is the difference between JpaRepository and CrudRepository using Spring Data JPA?

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:

@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?

Answer Source

Note that JpaRepository extends CrudRepository. Compare the JavaDoc of these two interfaces:

JpaRepository vs CrudRepository

In short JpaRepository

  • has additional JPA specific methods that support for example Query By Example , deleting in batches, manual flushing changes to database
  • querying methods return List's instead of Iterable's
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download