Hibernate/JPA:是否可以在单个查询中检索异构实体? [英] Hibernate/JPA: Is it possible to retrieve heterogeneous entities in a single query?
问题描述
我有 2 个实体:EntityA 和 EntityB.
I have 2 entities: EntityA and EntityB.
它们是不相关的,我不能将它们放在继承树中,因为有些限制超出了这个问题的范围.
They are unrelated, and I cannot put them in a Inheritance tree for some restrictions out of the scope of this question.
但是我需要在同一个 JPQL 或 HQL 查询中查询一个包含两个实体的所有实例的混合列表.这可以通过 JPA 甚至 Hibernate 直接实现吗?
But I need to get in the same JPQL or HQL query a mixed List containing all the instances of both entities. Is this possible with JPA or even Hibernate directly?
我需要这样的东西:
FROM EntityA WHERE fieldA=1
UNION
FROM EntityB WHERE fieldB="aa"
有什么提示吗?
推荐答案
好吧,我终于想通了.
让实体实现一个通用接口就足够了(甚至不需要在Hibernate上声明这个接口).
It is enought to make the entities implement a common interface (it is not even needed to declare this interface on Hibernate).
然后,可以进行这样的查询:
Then, a query like this can be done:
FROM my.package.CommonInterface obj
WHERE obj IN (FROM EntityA WHERE fieldA=1) OR
obj IN (FROM EntityB WHERE fieldB='a')
通过这种方式,您可以检索List
.
This way, you retrieve a List<CommonInterface>
.
问题解决了.
这篇关于Hibernate/JPA:是否可以在单个查询中检索异构实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!