Criteria子查询不为null

时间:2011-12-05 11:14:19

标签: hibernate criteria-api hibernate-criteria detachedcriteria

我想将以下子查询转换为使用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);
    

任何人都可以请我提供一个这种转换的例子,因为我读了一些例子,我仍然无法弄清楚如何做到这一点。

1 个答案:

答案 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子查询返回的结果集。