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

前端 未结 2 1340
你的背包
你的背包 2020-12-18 12:43

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.

相关标签:
2条回答
  • 2020-12-18 12:48

    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.

    0 讨论(0)
  • 2020-12-18 13:10

    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.

    0 讨论(0)
提交回复
热议问题