我有三个实体。那些是:
@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:
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'
在这种情况下,Account
实体与Organization
实体没有直接关系。 Account
实体通过Book
拥有关系。我如何使用hibernate条件动态查询来实现这一点?
答案 0 :(得分:13)
另一种方式
public List<Account> getAccountListByOrgName(String name){
return sessionFactory.getCurrentSession().createCriteria(Account.class)
.createAlias("book", "book")
.createAlias("book.organization", "organization")
.add(Restrictions.eq("organization.name", name))
.list();
}
答案 1 :(得分:10)
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();