通过 HQL 中远程相关集合的属性检索父元素?
大家早上好。我需要一些查询帮助。你可以假设我理解相对复杂的 SQL 查询,但是这个新奇的 HQL 东西让我有点困惑。
我有 5 个对象,A 到 E。我将使用小写字母(a 到 e)来引用这些对象中指向相同大写类型对象的属性。
在我的类结构中,A 具有对 B 的引用。B 具有对 C 的引用。C 具有 D 的集合(一对多)。并且 D 具有对 E 的引用。
/>D->E
A->B->C->D->E
\>D->E
...
在数据库上, D是关系表,存储了C和E的外键(通过反向属性Dc映射集合)。
我需要一个所有 As 的列表,其远亲 D 集合包含与特定 E 相关的 D。我做了这个伪查询(类似的东西在 MySQL 中可以工作)来说明问题:
select A
from D
left join E on D.e = E
left join C on D.c = C
left join B on B.c = C
left join A on A.b = B
where E = myfilter
但是,这不起作用,因为有HQL 中显然没有“on”。我尝试了在教程中找到的语法的变体,但 hibernate 总是抛出一些晦涩的错误或其他错误(无法取消引用集合、无效令牌、属性未映射 - 即使它是映射等)主要问题似乎是这样一个事实:我不需要根据集合中是否存在实际元素 (D) 进行过滤,而是根据一个属性 (E) 进行过滤。
有人知道如何提供帮助吗?如果您需要澄清,请发表评论。
Good morning, everyone. I need some query help. You can assume I understand relatively complex SQL queries, but this newfangled HQL thing is confusing me a little.
I have 5 objects, A to E. I'm going to use lower case letters (a to e) to refer to attributes in these objects that point to an object of the same upper-case type.
In my class structure, A has a reference to B. B has a reference to C. C has a collection (one to many) of D. And D has a reference to E.
/>D->E
A->B->C->D->E
\>D->E
...
On the database, D is a relationship table that stores the foreign keys of both C and E (the collection is mapped by the reverse attribute D.c).
I need a list of all As whose distantly related collection of D contains a D related to a specific E. I made this pseudoquery (something similar would work in MySQL) to illustrate the problem:
select A
from D
left join E on D.e = E
left join C on D.c = C
left join B on B.c = C
left join A on A.b = B
where E = myfilter
This doesn't work, however, because there is no 'on' in HQL apparently. I tried variants with syntaxes I found in tutorials but hibernate always throws some obscure error or another (can't dereference collection, invalid token, attribute is not mapped - even though it is, etc.) The main problem seems to be the fact that I don't need to filter by the presence of an actual element of the collection (D) but an attribute of one (E).
Does anyone know how to help? If you need clarification leave a comment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HQL中不需要
on
,因为HQL是用来遍历实体关联的,而Hibernate已经知道关联在数据库中是如何映射的。因此它会在生成的 SQL 中插入on
子句。您必须根据实体及其关联来思考,而不是根据表格来思考。所以你的查询应该是因为 e 需要不为空才能满足条件,所以使用左连接是没有意义的。内连接通常性能更高。
There is no need for
on
in HQL, because HQL is used to traverse entity associations, and Hibernate already knows how the associations are mapped in the database. So it inserts theon
clause in the generated SQL for you. You have to think in terms of entities and their associations instead of thinking in terms of tables. So your query should just besince e needs to be not null to satisfy the condition, there is no point in using left joins. inner joins are usually more performant.
你需要类似下面的东西(未经测试)
You need something like the following (not tested)