开发者

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 aNames of all A entities that are not referred to by B entities. Or in other words, all As 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 JOINs, 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜