Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Entity where Hibernate OneToOne association is not present

Tags:

hibernate

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?

like image 465
abudker Avatar asked Dec 27 '11 22:12

abudker


2 Answers

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"));
like image 190
JB Nizet Avatar answered Nov 15 '22 06:11

JB Nizet


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.

like image 35
Nehal Damania Avatar answered Nov 15 '22 07:11

Nehal Damania