Need help with formulating a JPA query, please
Given these two entities in a database accessed through Hibernate JPA,
@Entity class A {
int id;
String aName;
}
@Entity class B {
int id;
String bName;
@ManyToMany Set<A> aRefs;
}
the result I want is t开发者_如何学Pythonhe collection of the aName
s of all A entities that are not referred to by B entities. Or in other words, all A
s which are not part of any B
's aRefs
.
I've tried a number of alternatives using NOT EXISTS
and NOT MEMBER OF
with subselects and even dabbled with LEFT OUTER JOIN
s, but annoyingly enough the queries I come up with either get rejected by Hibernate's interpreter or even end up translated to invalid SQL that's rejected by Oracle.
This is from the top of my head - so I'm not sure if this will work or be a correct solution for you.
Add the other side of your relationship in entity A
@Entity class A {
int id;
String aName;
@ManyToOne B bref;
}
then you can create a ejb-ql statment to says something like "SELECT a FROM A a WHERE a.b is NULL"
3 people showed interest in this question, so I thought I'd share my answer. I arrived at this mostly by trial and error; I'm sorry to say I still don't "grok" the JPA Query Language.
2 queries that work are:
SELECT a FROM A a WHERE NOT EXISTS
(SELECT b FROM B b JOIN b.arefs ba WHERE a = ba)
and
SELECT a FROM A a WHERE a NOT IN
(SELECT ba FROM B b JOIN b.arefs ba)
精彩评论