简体   繁体   English

Hibernate:通过HQL获取延迟集合

[英]Hibernate : fetch lazy collection with HQL

I have two large tables (> 100 million rows each), let's call them Parent and Child (Parent with a lazy one to many relation to Child). 我有两个大表(每个表大于1亿行),我们称它们为“父级”和“子级”(父级与“子级”具有一对多的懒惰关系)。 The query is very slow when I use a join fetch and I also get a hibernate warning "HH000104 firstresult maxresults specified with collection fetch applying in memory" because I use a limit. 当我使用联接提取时,查询速度非常慢,并且由于使用了限制,因此我还收到休眠警告“ HH000104 firstcollection maxresults,该值是使用集合获取在内存中应用的”。

So I am trying to get the data in two separated queries: 所以我试图在两个单独的查询中获取数据:
- first query gets all parents with a limit -第一个查询使所有父母受到限制
- second query gets children with parent.id in the parent ids found by the first query -第二个查询获取在第一个查询找到的父ID中具有parent.id的子级

This solution performs very well, however hibernate does not aggregate the children with their parents, although the two queries are executed in the same session. 该解决方案执行得很好,但是尽管两个查询都是在同一会话中执行的,所以休眠状态不会将孩子与其父母聚合在一起。

I wonder if there is a way to achieve this using HQL or some java code: - I do not wish to use the criteria API (I would need to rewrite many queries and I find criteria API queries hard to maintain) - I do not want to change the Parent/Child relation to EAGER/BATCH because I would not be able to query the Parent without the Child 我想知道是否有一种方法可以使用HQL或一些Java代码来实现:-我不想使用标准API(我需要重写许多查询,而我发现很难维护标准API查询)-我不想要将父/子关系更改为EAGER / BATCH,因为如果没有子项,我将无法查询父项

Any idea ? 任何想法 ?

The second query should not get children only: Hibernate would have no way to know that all the children of each parent has been fetched. 第二个查询不应仅获取子代:Hibernate无法知道每个父代的所有子代均已获取。

The second query should get the parents with their children (but using an in clause selecting only the desired parents, and without limit): 第二个查询应该让父母和他们的孩子在一起(但使用in子句仅选择所需的父母,没有限制):

First query, with a limit applied: 第一个查询,有一个限制:

select distinct p.id from Parent p where ... 

Second query, with no limit applied: 第二个查询,没有限制:

select p from Parent p left join fetch p.children where p.id in :idsSelectedByTheFirstQuery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM