9

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 2
    See this http://stackoverflow.com/questions/14014086/what-is-difference-between-crudrepository-and-jparepository-interfaces-in-spring In short, it's the same, but extend `CrudRepository` unless you need JPA-specific features. – kaqqao Nov 02 '16 at 14:44

1 Answers1

9

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

If you are using JPA you should use JpaRepository.

Robert Niestroj
  • 15,299
  • 14
  • 76
  • 119
  • 1
    Especially the last part is wrong. By all means try to avoid the store specific interfaces as using them leaks the persistence technology into the client. Store specific interfaces should only be used if the tweaked functionality in them is really needed. See my other answer for details: http://stackoverflow.com/a/20784007/18122 – Oliver Drotbohm Nov 03 '16 at 21:38
  • Lesson learned - thak you Oliver – Robert Niestroj Nov 14 '16 at 20:22