Hibernate/JPA: Is it possible to retrieve heterogeneous entities in a single query?

坚强是说给别人听的谎言 提交于 2020-01-10 03:13:25

问题


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.

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?

I need somethign like this:

FROM EntityA WHERE fieldA=1
UNION
FROM EntityB WHERE fieldB="aa"

Any hint?


回答1:


Well, I finally figured it out.

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')

This way, you retrieve a List<CommonInterface>.

Problem solved.




回答2:


Best thing is to performs two queries.

But if you must:

You can create a POJO to retrieve them:

class EntityAandEntityB {
    EntityA a;
    EntityB b;
    long idA;
    long idB;
    int fieldA;
    String fieldB;

    public EntityAandEntityB(long idA, long IdB, int fieldA, String fieldB) {
       this.a = new EntityA(idA, fieldA);
       this.b = new EntityB(idB, fieldB);
    }
}

Then your query would be:

select new package.EntityAandEntityB(a.idA, a.fieldA, b.idB, b.fieldB) from ( 
    (select idA, fieldA from EntityA) a
UNION
    (select idB, fieldB from EntityB) b)

This is dirty and you probably must to look carefully the syntax.

Regards.



来源:https://stackoverflow.com/questions/7322526/hibernate-jpa-is-it-possible-to-retrieve-heterogeneous-entities-in-a-single-que

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!