如何使用hibernate标准连接多个表,其中实体关系不是直接的? [英] How to join Multiple tables using hibernate criteria where entity relationship is not direct?

查看:133
本文介绍了如何使用hibernate标准连接多个表,其中实体关系不是直接的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个实体。这些是:

I have three entities. those are:

@Entity
public class Organization {
    @Id
    private long id;
    @Column
    private String name;
}



@Entity
public class Book {
    @Id
    private Long id;
    @Column
    private String name;
    @ManyToOne
    private Organization organization;
}



@Entity
public class Account  {
   @Id
   private Long id;
   @Column
   private String name;
   @ManyToOne
   private Book book;
}

在这三个实体中,我想执行以下sql:

In these three entities I would like to perform following sql:

SELECT acc.name, acc.id
FROM account acc
JOIN book b on acc.book_id = b.id
JOIN organization org on b.organization_id = org.id
WHERE org.name = 'XYZ'

在这种情况下,帐户实体与组织无关实体直接。 帐户实体通过预订具有关系。如何使用hibernate条件动态查询来实现这一点?

In this case Account entity has no relation with the Organization entity directly. Account entity has the relation via Book. How can I achieve this using hibernate criteria dynamic query?

推荐答案

你可以这样做:

Criteria accountCriteria = getCurrentSession().createCriteria(Account.class,"acc");
Criteria bookCriteria =  accountCriteria .createCriteria("book","b");
Criteria orgCriteria =  bookCriteria.createCriteria("organization","org");
orgCriteria.add(Restrictions.eq("name", "XYZ"));

ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("name"));
properties.add(Projections.property("id"));

accountCriteria.setProjection(properties);
accountCriteria.list();

这篇关于如何使用hibernate标准连接多个表,其中实体关系不是直接的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆