存储库中的 Spring Data JPA 继承 [英] Spring Data JPA inheritance in repositories

查看:24
本文介绍了存储库中的 Spring Data JPA 继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 @MappedSuperClass 注释的抽象类.大约有 15 个实体扩展了这个抽象类(在数据库中有 15 个对应的表).这 15 个实体都具有从抽象超类继承的相同属性.

I have an abstract class annotated with @MappedSuperClass. There are around 15 entities that extend this abstract class (having 15 corresponding tables in the database). The 15 entities all have the same attributes that are inherited from the abstract super class.

我为抽象类创建了一个如下的存储库:

I have created a repository as below for the abstract class:

@NoRepositoryBean
public interface AbstractRepository <T extends AbstractClass, E extends Serializable>
                                    extends PagingAndSortingRepository<T, Serializable> {
  .....some methods here
}

这 15 个实体/表存储了一些数据(与 15 个独立设备有关的数据).根据所选设备,将检索该表中的数据.我是否必须为 15 个具体实体创建 15 个单独的存储库,或者有什么方法可以仅使用抽象存储库为所选设备获取特定实体?如果需要为每个具体实体创建存储库,如何为特定设备调用获取正确的存储库?(可能将表名和存储库类存储在应用程序启动时创建的映射中?)

The 15 entities/tables store some data (data pertaining to 15 separate equipment). Based on the equipment selected, the data from that table is to be retrieved. Will I have to create 15 separate repositories for the 15 concrete entities or is there any way to get the specific entity for the equipment selected using only the abstract repository? If repositories need to be created for each concrete entity, how to get the right repository for the specific equipment call? (store the table name and repository class in a map that gets created on startup of the application perhaps?)

推荐答案

您必须为每个类创建存储库.但是,您可以将方法保留在抽象中.您需要在每个方法上提供 @Query 并使用 SpeL(Spring 表达式语言)将类型添加到查询中.

You will have to create repository for each class. However you can keep your methods in the abstract. You'll need to provide @Query on each of the methods and use SpeL(Spring Expression Language) to add the type to the queries.

@NoRepositoryBean
public interface AbstractRepository<T extends AbstractEquipment> 
        extends CrudRepository<T, Long>{

 @Query("select e from #{#entityName} as e from equipment where e.name = equipmentName")
 T findEquipmentByName(String equipmentName);

}

然后像下面这样扩展

@Transactional
public interface SpecialEquipmentRepo extends AbstractRepository<SpecialEquipment,Long>{

}

这篇关于存储库中的 Spring Data JPA 继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆