java - 抽象类中的 Hibernate NamedQuery

标签 java postgresql hibernate

我有 20 个继承自 AbstractEntity 的类,它们都需要具有相同的 NamedQueries,作为示例,我们举一个简单的例子:

@NamedQuery(name = Bootle.FIND_BY_ID, query = //
        "SELECT entity FROM " + Bootle.ENTITY_NAME + " entity " + 
        "LEFT OUTER JOIN FETCH entity.value val " + 
        "..." +
        "WHERE entity.id = :pIds AND entity.relationable = :pBoolean")

我希望我可以将这些查询移至 AbstractEntity,但是我无法确定 hibernate 的 EntityName。理想的解决方案是以某种方式拥有它:

@NamedQuery(name = BaseDAO.FIND_BY_ID, query = //
            "SELECT entity FROM " + AbstractEntity.ENTITY_NAME + " entity " + 
            "LEFT OUTER JOIN FETCH entity.value val " + 
            "..." +
            "WHERE entity.id = :pIds AND entity.relationable = :pBoolean")

但是上面的例子不起作用。当我查询此方法时,Hibernate 本身可以给出正确的实体名称吗?

当前查询调用的示例:

getEntityManager().createNamedQuery(BaseDAO.FIND_BY_ID)
                .setParameter("pId", 201L)
                .setParameter("pBoolean", false);

最佳答案

来自文档。 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query.spel-expressions

To avoid stating the actual entity name in the query string of a @Query annotation, you can use the #{#entityName} variable.

The entityName can be customized by using the @Entity annotation. Customizations in orm.xml are not supported for the SpEL expressions. Of course, you could have just used User in the query declaration directly, but that would require you to change the query as well. The reference to #entityName picks up potential future remappings of the User class to a different entity name (for example, by using @Entity(name = "MyUser").

Another use case for the #{#entityName} expression in a query string is if you want to define a generic repository interface with specialized repository interfaces for a concrete domain type. To not repeat the definition of custom query methods on the concrete interfaces, you can use the entity name expression in the query string of the @Query annotation in the generic repository interface.

示例

@MappedSuperclass
public abstract class AbstractMappedType {
  …
  String attribute
}

@Entity
public class ConcreteType extends AbstractMappedType { … }

@NoRepositoryBean
public interface MappedTypeRepository<T extends AbstractMappedType>
  extends Repository<T, Long> {

  @Query("select t from #{#entityName} t where t.attribute = ?1")
  List<T> findAllByAttribute(String attribute);
}

public interface ConcreteRepository
  extends MappedTypeRepository<ConcreteType> { … }

关于java - 抽象类中的 Hibernate NamedQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57182074/

相关文章:

java - CGLIB如何代理String或其他final类?

python - SQLAlchemy:按 JSON 列中的键过滤

sql - 检查一些多边形是否相互重叠

postgresql - postgres 和意外的 to_tsquery 匹配

java - 在 Hibernate 中使用 Generation 注释时序列不存在异常

java - 5.0.0 以下版本的 Hibernate Karaf 功能

java - Gradle:如何管理对测试实用程序的循环依赖

java - PlusClient.OnPeopleLoadedListenter 无法解析为类型

java - 如何适当调整自定义组件的大小?

java - Java 中的 DecimalFormat 与 #####0.00 模式的奇怪行为