【问题标题】:Can I have a single JPA repository interface handling multiple entity classes using Spring Data JPA?我可以让一个 JPA 存储库接口使用 Spring Data JPA 处理多个实体类吗?
【发布时间】:2020-07-07 02:48:06
【问题描述】:

我不太喜欢 Spring Data JPA,并且在处理 Spring Boot 项目时遇到以下问题。

我对如何正确处理这种情况有以下架构疑问:

我有一个由这样的接口实现的存储库,我在其中定义我的“查询方法”:

public interface ExcelRepository extends CrudRepository<Country, Integer> {

    public List<Country> findAllByOrderByCountryNameAsc();

    public List<BlockAttackDetail> findAllByOrderByAttackTypeAcronymAsc();
}

如您所见,我正在扩展 CrudRepository 接口,并指定了一个名为 **Country* 的模型类,用于映射我的数据库中的特定表。

我添加了第二种方法,该方法适用于映射不同数据库表的另一个实体类 (BlockAttackDetail)。

因此,启动我的应用程序时,我收到此错误,因为此存储库仅适用于 Country 实体类映射的数据库表:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property attackTypeAcronym found for type Country!

我的问题是:我是要创建多个 JPA 存储库接口(每个实体一个)还是有办法让单个 JPA 存储库接口处理多个实体类?

在我的具体情况下,我将使用很少的方法与特定数据库表(与实体)交互,并且我不希望有一个存储库接口来处理多个实体类(以避免混淆)。

我能以某种方式做到这一点吗?如果我能做到,从架构的角度来看是否有意义,或者最好为每个实体类提供一个特定的 JPA 存储库接口?

【问题讨论】:

  • 每个实体都需要一个存储库。

标签: java spring spring-boot jpa spring-data-jpa


【解决方案1】:

根据 Spring Data 文档,您应该为每个实体拥有一个存储库

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.definition

在您的情况下,完成工作的唯一方法是使用 Spring Data JPA:

public interface CountryRepository extends CrudRepository<Country, Integer> {

   public List<Country> findAllByOrderByCountryNameAsc();
}

public interface BlockAttackDetailRepository extends CrudRepository<BlockAttackDetail, Integer> {

   public List<BlockAttackDetail> findAllByOrderByAttackTypeAcronymAsc();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多