JPA join entity on the same entity

2019-06-05 08:17发布

问题:

I have a question about JPQL. I need to join entity on the same entity. Entity.child_id is mapped as a collection in JPA entity class, i.e. entity have a collection property ("children") which holds every child. Join works fine with this collection (don't know why, by the way), for example:

SELECT parent.id, child FROM Entity parent JOIN parent.children child

The question is, is there a way to write this query without JOIN, something like this:

SELECT parent.id, child FROM Entity parent, Entity child WHERE <condition>

I don't know how to construct a condition. "parent.children = child" doesn't work - the left side is collection and the right side is a single entity. Something like "child IN (parent.children)" has to be used, I guess, but I don't know how to do this exactly. I need it because I can't combine general join with another joins in more complicated query. Thanks in advance!

回答1:

Ok, I'll answer myself.

1st way:

SELECT parent.id, child FROM Entity parent, IN(parent.children) child

2nd way:

SELECT parent.id, child FROM Entity parent, Entity child WHERE child MEMBER OF parent.children

Only the 2nd query is extremely dangerous, it generates very heavy cross-join sql query with IN. If somebody has a better solution - I'd really apreciate if you share, I haven't solved the whole task yet.



标签: join jpql