JPA join entity on the same entity

2019-06-05 07:49发布

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!

标签: join jpql
1条回答
家丑人穷心不美
2楼-- · 2019-06-05 08:42

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.

查看更多
登录 后发表回答