我可以使用Spring Data JPA使用一个JPA存储库接口来处理多个实体类吗? [英] Can I have a single JPA repository interface handling multiple entity classes using Spring Data JPA?
问题描述
我对 Spring Data JPA 不太满意,并且在 Spring Boot 项目上工作时遇到以下问题.
I am not so into Spring Data JPA and I have the following problem working on a Spring Boot project.
对于如何正确处理这种情况,我有以下架构疑问:
I have the following architectural doubt about how to correctly handle this kind of situation:
我有一个通过这样的接口实现的存储库,其中定义了我的查询方法":
I have a repository implemented by an interface like this in which I am defining my "query methods":
public interface ExcelRepository extends CrudRepository<Country, Integer> {
public List<Country> findAllByOrderByCountryNameAsc();
public List<BlockAttackDetail> findAllByOrderByAttackTypeAcronymAsc();
}
如您所见,我正在扩展 CrudRepository 接口,并且指定了一个名为** Country *的模型模型,该模型类映射了数据库中的特定表.
As you can see I am extending the CrudRepository interface and I specified a single model class named **Country* mapping a specific table on my database.
我添加了第二种方法,该方法在另一个实体类( BlockAttackDetail )上映射另一个数据库表.
I added a second method working on another entity class (BlockAttackDetail) mapping a different database table.
因此,启动我的应用程序会收到此错误,因为此存储库仅用于 Country 实体类所映射的数据库表:
So starting my application I obtain this error because this repository is intended only for the database table mapped by the Country entity class:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property attackTypeAcronym found for type Country!
我的问题是:我是否要创建多个JPA存储库接口(每个实体一个),或者存在一种方法来使单个JPA存储库接口可以在多个实体类上工作?
My problem is: have I to create multiple JPA repositories interfaces (one for each entity) or exist a way to have a single JPA repository interface working on multiple entity classes?
在我的特定情况下,我将很少有方法可以与特定的datbase表(具有实体)进行交互,并且我预想到有一个用于处理多个实体类的单一存储库接口(以避免混淆).
In my specific case I will have few methods that will interact with a specific datbase table (with an entity) and I prefear have a single repository interface handling multiple entity classes (to avoid confusion).
我能以某种方式做到吗?如果我可以做到,那么从体系结构的角度讲还是有意义的,或者最好为每个实体类都有一个特定的JPA存储库接口?
Can I do it in some way? And if I can do it make it sense from an architectural point of view or it is better have a specific JPA repository interface for each entity class?
推荐答案
根据Spring Data文档,您应该为每个实体拥有一个存储库
According to Spring Data documentation you should have one repository for each entity
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.definition
对于您而言,完成工作的唯一方法是使用Spring Data JPA:
In your case the only way to do your job is with 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();
}
这篇关于我可以使用Spring Data JPA使用一个JPA存储库接口来处理多个实体类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!