JPA 在同一实体上加入实体
我有一个关于 JPQL 的问题。我需要在同一实体上加入实体。 Entity.child_id 映射为 JPA 实体类中的集合,即实体具有保存每个子项的集合属性(“children”)。 Join 可以很好地处理这个集合(顺便说一句,不知道为什么),例如:
SELECT parent.id, child FROM Entity parent JOIN parent.children child
问题是,有没有办法在不使用 JOIN 的情况下编写此查询,如下所示:
SELECT parent.id, child FROM Entity parent, Entity child WHERE <condition>
我不知道如何构造条件。 “parent.children = child”不起作用 - 左侧是集合,右侧是单个实体。我想,必须使用“child IN (parent.children)”之类的东西,但我不知道该怎么做。我需要它,因为我无法将常规联接与更复杂的查询中的另一个联接结合起来。 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我自己来回答。
第一种方式:
第二种方式:
只有第二个查询是极其危险的,它会生成非常重的带有 IN 的交叉连接 sql 查询。
如果有人有更好的解决方案 - 如果您分享,我真的很感激,我还没有解决整个任务。
Ok, I'll answer myself.
1st way:
2nd way:
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.