简体   繁体   中英

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). 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.

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

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

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.

The second query should get the parents with their children (but using an in clause selecting only the desired parents, and without limit):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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