Files
hibernate-demo/one-to-many/output/06-multiple-bag-h7.txt
T

28 lines
1.6 KiB
Plaintext

# MultipleBagFetchException and three fixes (3 employees, 4 projects per department)
# Hibernate ORM 7.4.16.Final, H2, JDK 25
== The failure: two Lists, two join fetches
exception: java.lang.IllegalArgumentException <- org.hibernate.loader.MultipleBagFetchException
message: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [com.ankurm.onetomany.Variants$BagDept.employees, com.ankurm.onetomany.Variants$BagDept.projects]
-- SQL sent before the exception
(no SQL)
== Fix 2: split into two queries (same Lists)
employees=3 projects=4
-- two queries, one collection each
sql> select bd1_0.id,e1_0.dept_id,e1_0.id,e1_0.name from BagDept bd1_0 left join BagEmp e1_0 on bd1_0.id=e1_0.dept_id
sql> select bd1_0.id,p1_0.dept_id,p1_0.id,p1_0.title from BagDept bd1_0 left join BagProject p1_0 on bd1_0.id=p1_0.dept_id where bd1_0.id in (?)
== Fix 1: Set instead of List
employees=3 projects=4
-- one query, two join fetches
sql> select sd1_0.id,e1_0.dept_id,e1_0.id,e1_0.name,p1_0.dept_id,p1_0.id,p1_0.title from SetDept sd1_0 left join SetEmp e1_0 on sd1_0.id=e1_0.dept_id left join SetProject p1_0 on sd1_0.id=p1_0.dept_id
rows the database returned for that one query: 12 (3 x 4: the Cartesian product Hibernate then folds back into 3 + 4 objects)
== Fix 3: keep Lists, drop the join fetch, add @BatchSize
employees=3 projects=4
-- query the parents, touch both collections
sql> select bd1_0.id from BatchDept bd1_0
sql> select e1_0.dept_id,e1_0.id,e1_0.name from BatchEmp e1_0 where e1_0.dept_id=?
sql> select p1_0.dept_id,p1_0.id,p1_0.title from BatchProject p1_0 where p1_0.dept_id=?