休眠标准左边排除JOIN

时间:2013-12-16 12:52:16

标签: java hibernate join hibernate-criteria

我不知道如何使用Hibernate Criteria

SELECT * 
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL

有像

这样的Hibernate映射
@Entity
class A{

    @Id
    @Column(name = "ID")
    private String ID;

    ... // fields
}

@Entity
class B{
    ... // fields

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "A_ID", referencedColumnName = "ID")
    @Cascade(CascadeType.DETACH)
    private A a;

    ... // fields
}

所以我需要得到所有A的列表,而不是B

1 个答案:

答案 0 :(得分:2)

之前没有尝试过,但这样的事情应该有效:

select * from Table_A a
where a not in (
   select b.a from Table_B b )

这当然是在HQL中

标准可能如下所示:

DetachedCriteria subquery = DetachedCriteria.forClass(B.class)
.setProjection( Property.forName("a.ID") )
.add(Restrictions.isNotNull("a.ID"));

session.createCriteria(A.class)
.add ( Property.forName("ID").notIn(subquery) )
.list();