首页 文章

使用Hibernate Criteria加入两个表

提问于
浏览
4

采用以下示例实体:

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

Entity Parent {
    long id;
    String desc;
}

有没有办法使用Hibernate Criteria查询:

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

我们主要关注的是 how to do join with Criteria across two entities that are only related by the long key .

假设我们 can't 直接在我们的Child中引用了Parent .

1 回答

  • 1

    好吧,不确定你指的是什么Hibernate版本,但在JPA 2.0中这样的事情是可能的:

    String query = "SELECT c FROM Child c, Parent p WHERE c.parentId = p.id";
    
    List<Child> children = em.createQuery(query, Child.class).getResultList();
    

    通过这种方式,您可以根据自定义条件明确地进行JOIN,而不是让JPA管理它,尽管这样做是完全合法的 .

相关问题