Efficiently download a large batch of OneToMany collections right away with Hibernate

I have a Parent object with @OneToMany relation with a Child object. Most of the time when I need to work with Parent s Child objects, Im works with a single parent, so lazy fetching ( FetchMode.SELECT ) is suitable.

However, I have a situation where Im requests a large number of Parent (sometimes hundreds or even thousands), and I need to work with their Child objects. FetchMode.SELECT gives me a serious N + 1 problem, so I need to do something else in this scenario. If I did this through JDBC, then I would be the only query for Parent records, and then another query for all Child records using the IN statement ( where child.parentid in (?,?,?....) ). I need active Hibernate objects because Hibernate Search will call getChildren () as part of the indexing process.

The following options are considered:

  • Criteria.setFetchMode("children", FetchMode.JOIN) (or join fetch in HQL) would give me a Cartesian product that is cruel with a lot of entities.
  • Adding @BatchSize to Parent.getChildren() will help for my big batch script, but this is not the strategy I want to use for normal operations. Itd is ideal if I could set the batch size to retrieve in my / HQL criteria, but I cannot find a way to do this.
  • Using FetchMode.SUBSELECT in Parent.getChildren() is very similar to @BatchSize , it would be great for my big batch script, but not suitable for normal operations, and I cannot find a way to use it with criteria / HQL (criteria and annotations the object uses different FetchMode enumerations, despite the duplicate name).

TL; DR; I have a one-to-many relationship with the lazy choice mode, but sometimes I want to be able to efficiently load relationships for many objects at once.

+5
source share

Source: https://habr.com/ru/post/1235144/


All Articles