9

次のサブクエリを 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);
    

いくつかの例を読んでも、まだその方法がわからないので、この変換の例を教えてください。

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プロパティは、サブクエリによって返された結果のセットでidなければなりません。in

于 2011-12-05T11:58:49.460 に答える