I have a Parent
entity with a @OneToMany
relationship with a Child
entity. Most of the time, when I need to work with a Parent
’s Child
entities, I’m working with a single parent, so lazy fetching (FetchMode.SELECT
) is appropriate.
However, I have a situation where I’m querying a large number of Parent
s (sometimes hundreds or even thousands), and I need to work with their Child
entities. FetchMode.SELECT
gives me a serious N+1 problem, so I need to do something different in this scenario. If I were doing this via JDBC, it’d be single query for the Parent
records, then another query for all the Child
records using an IN
statement (where child.parentid in (?,?,?....)
). I need live Hibernate entities, because Hibernate Search is going to call getChildren() as part of its indexing process.
The options I’ve considered are:
Criteria.setFetchMode(“children”, FetchMode.JOIN)
(orjoin fetch
in HQL) - this would give me a cartesian product, though, which is brutal with that many entities.- Adding
@BatchSize
toParent.getChildren()
- this would help for my big batch scenario, but it isn’t really the strategy I want to use for normal operations. It’d be perfect if I could set a batch size for the fetch in my Criteria/HQL, but I can’t find a way to do so. - Using
FetchMode.SUBSELECT
inParent.getChildren()
- much like@BatchSize
, this would be great for my big batch scenario, but isn’t appropriate for normal operations, and I can’t find a way to use it with Criteria/HQL (Criteria and the entity annotations use different FetchMode enums, despite the duplicate name).
tldr; I have a one-to-many relationship with a lazy fetch mode, but sometimes I want to be able to efficiently load the relationship for many entities at once.
createNativeQuery()
and be done with it. Hibernate is convenient to use, but can quickly become inefficient.