9

我想将以下子查询转换为使用休眠子查询:

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);
    

谁能给我一个这个转换的例子,因为我读了一些例子,但我仍然不知道如何做到这一点。

4

1 回答 1

22
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创建一个限制:被搜索员工的属性必须idin子查询返回的结果集。

于 2011-12-05T11:58:49.460 回答