我想将以下子查询转换为使用hibernate子查询:
getCurrentSession().createQuery("from Employee where id in (select adminId from Department where adminId is not null)")
.list();
员工:
@ManyToOne
@JoinColumn(name = "fk_department_id", nullable = true)
private Department department;
系:
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "fk_department_id")
private Set<Employee> employees = new HashSet<Employee>(0);
任何人都可以请我提供一个这种转换的例子,因为我读了一些例子,我仍然无法弄清楚如何做到这一点。
答案 0 :(得分:20)
Criteria c = session.createCriteria(Employee.class, "e");
DetachedCriteria dc = DetachedCriteria.forClass(Departemt.class, "d");
dc.add(Restrictions.isNotNull("d.adminId");
dc.setProjection(Projections.property("d.adminId"));
c.add(Subqueries.propertyIn("e.id", dc));
setProjection
调用使子查询仅返回adminId
属性而不是整个Department
实体。 Subqueries.propertyIn
创建了一个限制:搜索到的员工的属性id
必须是in
子查询返回的结果集。