Spring 数据 JPA 自定义查询中 "the entity" 的占位符

A placeholder for "the entity" in Spring Data JPA custom queries

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

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

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数据支持在查询定义中使用Spring SPEL表达式。

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

We support the following list of variables to be used in a manual query

[entityName]

select x from #{#entityName} x

Inserts the entityName of the domain type associated with the given Repository. The entityName is resolved as follows: If the domain type has set the name property on the @Entity annotation then it will be used. Otherwise the simple class-name of the domain type will be used.

因此:

public class EntityARepository extends JPARepository<A,IDClass>{

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