如何将 HQL 中引用的实体转换为其子类

Ami*_*deh 5 java hibernate jpa hql

假设有以下实体(不写JPA注解):

class Questionnaire {
    ...
}

class Policy {
    private Questionnaire questionnaire;
    ...
}

class LifeQuestionnaire extends Questionnaire {
    private String someField;
}

class LifePolicy extends Policy {  
    ...
}
Run Code Online (Sandbox Code Playgroud)

看起来政策引用了调查问卷,但 aLifePolicy引用了LifeQuestionnaire(此限制始终正确)。

有什么办法可以编写这样的查询:

from LifePolicy lplc
where ((LifeQuestionnaire) lplc.questionnaire).someField = :fieldValue
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我希望在 HQL 查询中进行某种类型的转换,因为someField仅在LifeQuestionnaire.

Ben*_*Ben 1

我遇到了完全相同的问题,并且找到了适合我的解决方案。它不是很好,但是很有效。尝试使用“交叉”连接。例如

select (specify what you want to fetch) 
from LifePolicy as lp, LifeQuestionnaire as lqn 
inner join lqn.questionnaire as q 
where lqn.id = lp.id 
and q.someField = :fielfValue
Run Code Online (Sandbox Code Playgroud)

来源:

https://www.jumpingbean.co.za/blogs/mark/hibernate https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-from