sql - jpa 对子类的连接查询

标签 sql hibernate jpa polymorphism polymorphic-associations

我在 JPA( hibernate )中有以下关系。

对象 X 有两个子类,Y 和 Z。

对象 A 与对象 X 具有多对一关系。(注意,这是一种单方面关系,因此对象 X 无法看到对象 A)。

现在,我想获取对象 A 中列的最大值,但仅限于关系属于特定子类型的情况,即...Y。

所以,这等同于……在对象 A 中,在它们与 Y 有关系的所有 A 实例中获取 column1 的最大值。这可能吗?我对如何查询它有点迷茫。

我在想这样的事情:

String query = "SELECT MAX(a.columnName) FROM A a join a.x;
Query query = super.entityManager.createQuery(query);
query.execute();

然而,这并没有考虑到 X 的子类......所以我有点迷茫。

任何帮助将非常感激。

最佳答案

JPA 2.0 允许查询使用 TYPE 运算符限制从多态查询返回的类。从 JPA 2.0 规范:

4.6.17.4 Entity Type Expressions

An entity type expression can be used to restrict query polymorphism. The TYPE operator returns the exact type of the argument.

The syntax of an entity type expression is as follows:

entity_type_expression ::=
         type_discriminator |
         entity_type_literal |
         input_parameter
type_discriminator ::=
         TYPE(identification_variable |
                single_valued_object_path_expression |
                input_parameter )

An entity_type_literal is designated by the entity name.

The Java class of the entity is used as an input parameter to specify the entity type.

Examples:

SELECT e
FROM Employee e
WHERE TYPE(e) IN (Exempt, Contractor)

SELECT e
FROM Employee e
WHERE TYPE(e) IN (:empType1, :empType2)

SELECT e
FROM Employee e
WHERE TYPE(e) IN :empTypes

SELECT TYPE(e)
FROM Employee e
WHERE TYPE(e) <> Exempt


JPA 1.0 不提供这种机制,因此如果您使用 JPA 1.0,则使用标准 JPQL 将无法实现。

如果您不介意使用专有 HQL,那么您可以使用特殊属性 class :

Likewise, the special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.

from Cat cat where cat.class = DomesticCat


所以在你的情况下,我会尝试这样的事情:
SELECT MAX(a.columnName) FROM A a where a.x.class = Y

关于sql - jpa 对子类的连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2957271/

相关文章:

mysql - 优化 Hive 查询

sql - MongoDB : few questions

MySql DB 查询优化器和 like 关键字

grails - 使用JPA 1.0的Grails 2.1.1

spring - CrudRepository 不从 schema.sql 读取数据

sql - 让 Hibernate 绑定(bind)参数类型 "char(1)"而不是 "nvarchar(4000)"?

java - 如何使用 JUnit 与 Spring 和 Hibernate 来模拟事务的结束以隔离 LazyInitializationException?

java - 如果没有从父存储库中显式刷新,对父的修改不会持久

java - 如何更新 JPA 实体

mysql - sql 表的命名约定