Question

I have no ideas how to do it using Hibernate Criteria

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

there is Hibernate mapping like

@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
}

So I need to get list of all A which are not referred by B

Was it helpful?

Solution

Not tried it before, but something like this should work:

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

This is of course in HQL

Criteria might look like this:

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top