Join two tables with Hibernate Criteria

Take the following example entities:

Entity Child {
    long id;
    String name;
    long parentKey;
}

Entity Parent {
    long id;
    String desc;
}

Is there a way with Hibernate Criteria queries:

select * from Child c, Parent p 
         where c.parentKey = p.id and c.name = "whatever" and p.desc = "whatever"

Our main concern is how to do join with Criteria across two entities that are only related by the long key .

Assume that we can't put a reference to Parent directly in our Child.


Well, not sure what Hibernate version are you referring to, but in JPA 2.0 something like this is possible:

String query = "SELECT c FROM Child c, Parent p WHERE c.parentId = p.id";

List<Child> children = em.createQuery(query, Child.class).getResultList();

In this way you're explicitly doing JOIN based on your custom condition instead of letting JPA manage it, albeit it's perfectly legal to do so.

链接地址: http://www.djcxy.com/p/37076.html

上一篇: Hibernate Criteria Query for Self Referencing Entity; 错误的结果

下一篇: 使用Hibernate Criteria加入两个表