I have two classes with a bi-directional @OneToOne mapping to each other.
Class A {
@OneToOne(fetch = FetchType.Lazy, mappedBy="a")
private B b;
}
Class B {
@OneToOne(fetch = FetchType.Eager)
private A a;
}
I need to write code to retrieve all instance of B which to do not have an instance of A associated with them. I also need to write a similar query for all A which have no B.
I have tried:
Criteria criteria = getSession().createCriteria(B.class)
criteria.add(Restrictions.isNull("a")
but this seems to always return null. Thoughts?
This should work, for both directions:
Criteria criteria = session.createCriteria(B.class, "b");
criteria.createAlias("b.a", "a", Criteria.LEFT_JOIN);
criteria.add(Restrictions.isNull("a.id"));
There is a documented problem in Hibernate, which says that "The query language IS NULL syntax won't work with a one-to-one association!"
Also, there is a pending Jira on the same issue JIRA
Till this gets fixed, the workaround provided by JB Nizet works great.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With