JPA加入实体在同一实体上 [英] JPA join entity on the same entity

查看:110
本文介绍了JPA加入实体在同一实体上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JPQL有疑问.我需要在同一实体上加入实体. Entity.child_id被映射为JPA实体类中的集合,即,实体具有一个集合属性(子项"),该属性包含每个子项. Join在此集合中工作得很好(顺便说一句,不知道为什么),例如:

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

问题是,有没有一种方法可以在不使用JOIN的情况下编写此查询,如下所示:

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>

我不知道如何构造条件. "parent.children = child"不起作用-左侧是集合,右侧是单个实体.我猜必须使用"child IN(parent.children)"之类的东西,但是我不知道该怎么做.我需要它,因为我无法在更复杂的查询中将普通联接与另一个联接结合在一起. 预先感谢!

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!

推荐答案

好,我会回答自己.

第一种方式:

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

第二种方式:

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

只有第二个查询非常危险,它会使用IN生成非常繁重的交叉联接sql查询. 如果有人有更好的解决方案-如果您与我分享,我将不胜感激,但我还没有解决整个任务.

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.

这篇关于JPA加入实体在同一实体上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆