【问题标题】:What exactly is the difference between JpaRepository and CrudRepository using Spring Data JPA? [duplicate]使用 Spring Data JPA 的 JpaRepository 和 CrudRepository 之间到底有什么区别? [复制]
【发布时间】: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

JpaRepositoryCrudRepository 之间到底有什么区别?什么是最好的选择,或者在什么情况下最好使用一个而不是另一个选择?

另一个疑问是:为什么我定义的 DAO 接口扩展了本身就是接口的 JpaRepositoryCrudRepository?据我所知,接口已实现而不是扩展......我错过了什么?

【问题讨论】:

标签: spring spring-data spring-data-jpa


【解决方案1】:

请注意,JpaRepository 扩展了 CrudRepository。比较这两个接口的JavaDoc:

JpaRepository vs CrudRepository

简而言之JpaRepository

  • 具有额外的 JPA 特定方法,例如支持 Query By Example、批量删除、手动刷新数据库更改
  • 查询方法返回List's 而不是Iterable's

如果您使用 JPA,则应使用 JpaRepository。

【讨论】:

  • 尤其是最后一部分是错误的。尽一切努力避免使用商店特定的接口,因为使用它们会将持久性技术泄漏到客户端中。仅当确实需要其中的调整功能时,才应使用商店特定的接口。详情见我的其他回答:stackoverflow.com/a/20784007/18122
  • 吸取的教训 - 谢谢你,奥利弗
猜你喜欢
  • 2012-12-10
  • 1970-01-01
  • 2016-01-18
  • 2021-11-11
  • 1970-01-01
  • 2016-09-12
  • 2016-08-12
相关资源
最近更新 更多