【发布时间】:2017-03-15 22:19:47
【问题描述】:
我正在开发一个 Spring Boot 应用程序,该应用程序使用 Spring Data JPA(在 Hibernate 4 上)访问我的数据库。
我的疑问与 DAO 接口(JPA 用于自动生成查询)有关。
所以,在我的项目中,我有这两个接口:
1) 住宿DAO:
@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);
}
它们都可以正常工作并使用相同的逻辑来声明查询。
我唯一的疑问是:第一个扩展 JpaRepository 而第二个实现 CrudRepository。
JpaRepository 和 CrudRepository 之间到底有什么区别?什么是最好的选择,或者在什么情况下最好使用一个而不是另一个选择?
另一个疑问是:为什么我定义的 DAO 接口扩展了本身就是接口的 JpaRepository 和 CrudRepository?据我所知,接口已实现而不是扩展......我错过了什么?
【问题讨论】:
-
看这个stackoverflow.com/questions/14014086/… 简而言之,它是一样的,但是扩展
CrudRepository,除非你需要特定于JPA的功能。
标签: spring spring-data spring-data-jpa