Spring Data JPA定制查询中“实体”的占位符

问题描述 投票:0回答:1

假设我的许多实体共享一个公共属性。

对于每个存储库,我正在编写一个自定义查询以根据该自定义属性清除实体。

public class EntityA {
    private ? commonAttr;
}

public class EntityARepository extends JPARepository<A,IDClass>{

    @Modifying
    @Query("delete from EntityA where commonAttr : value")
    int deleteByCommonAttr(@Param("value") ? value)
}

假设共享相同属性的实体是一打。当前,我必须将方法复制并粘贴到所有存储库中,并用要在其上运行自定义查询的每个实体替换EntityA

我想知道是否可以在@Query批注中用占位符替换实体名称。

这具有双重好处:1)如果我必须复制并粘贴代码,则可以将片段粘贴到所有存储库中,而无需再次检查(等于更少的错误),以及2)我可以尝试为该存储库创建超级存储库接口。共有共同属性的实体。

spring-data-jpa jpql
1个回答
0
投票

Spring Data支持在查询定义中使用Spring SPEL表达式。

https://docs.spring.io/spring-data/data-jpa/docs/1.7.x/reference/html/#jpa.query.spel-expressions

我们支持以下手册中使用的变量列表查询...... entityName

select x from #{#entityName} x

插入与给定关联的域类型的entityName存储库。实体名称解析如下:如果域类型已经在@Entity注释上设置了name属性,那么它将是用过的。否则,将使用域类型的简单类名。

因此:

public class EntityARepository extends JPARepository<A,IDClass>{

    @Modifying
    @Query("delete from #{#entityName} where commonAttr : value")
    int deleteByCommonAttr(@Param("value") ? value)
}
© www.soinside.com 2019 - 2024. All rights reserved.