Add one-to-many module: @OneToMany in Hibernate 7.4.16.Final (unidirectional join table vs @JoinColumn vs mappedBy, Set vs List removal cost, sync helper, fetch defaults, N+1, MultipleBagFetchException fixes, id-hashCode trap)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4H5ph3J7k2MJnRuVH
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
bdae169002
commit
eab5461d86
@@ -0,0 +1,27 @@
|
||||
# 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=?
|
||||
Reference in New Issue
Block a user