@OneToMany, ran the code, and the SQL log shows something you did not expect: a third table, a stack of update statements, or one delete followed by a dozen inserts after you removed a single child. This page explains why, from the ground up, with the SQL Hibernate really sent.
Every statement and every count below comes from a test in a companion module that runs plain Hibernate on an in-memory H2 database. The tests assert the same numbers they print, so a figure on this page that stops being true fails the build. Read top to bottom: each section uses what the one before it taught, and the dull-looking fact about who owns the foreign key in the first section is what explains the silent bug in the third.
Tested against. Hibernate ORM7.4.16.Final(the newest 7.x GA listed inmaven-metadata.xmlon 2026-11-16;8.0.0.CR1is listed after it but is a candidate release and was not tested), Jakarta Persistence3.2.0, H22.4.240, JUnit6.0.3, JDK 25 (Temurin 25.0.5+8). Companion module: hibernate-demo/one-to-many.
A @OneToMany is a foreign key, and one side owns it
A department has many employees. In a relational database that is one thing: anemployees table with a dept_id column that points at departments.id. There is no “list of employees” stored anywhere in the departments table.
Java wants to see it from both ends: a Department with a collection of employees, and an Employee with a department. That gives you two Java fields describing one database column. Hibernate needs to know which of the two it should trust when it writes dept_id. The one it trusts is called the owning side, and it is always the @ManyToOne field. The @OneToMany side is the inverse side, and mappedBy is how you say so.
Employee.department field writes it. Keep that sentence in mind; the sync-helper section and the Set section both come back to it.
The inverse side, from Department.java:
// mappedBy = "department" names the field on Employee that owns the foreign key column.
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Employee> employees = new HashSet<>();
The owning side, from Employee.java:
// LAZY: the JPA default for @ManyToOne is EAGER; this line is what opts out.
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dept_id")
private Department department;
Every database call needs a transaction. Lazy collections and proxies can only be read while the session is open. Touchdepartment.getEmployees()after the transaction has ended and you getLazyInitializationException. Put@Transactionalon your service method, or open the transaction yourself, before reading a collection.
Setup: dependency and prerequisites
Hibernate 7 needs Java 17 or newer, and every annotation on this page comes from thejakarta.persistence package (the old javax.persistence namespace is gone). The module declares its versions in pom.xml:
<hibernate.version>7.4.16.Final</hibernate.version>
<persistence.version>3.2.0</persistence.version>
The companion module runs on JDK 25 because that is the current LTS. The mappings themselves need nothing newer than Java 17.
- Department.java and Employee.java, the full entities
- Hibernate 7 association mappings, all four association types in one guide
- Hibernate User Guide: one-to-many
The same relationship mapped three ways sends different SQL
You can write a one-to-many withoutmappedBy, and Hibernate will still make it work. It just has to put the foreign key somewhere, and there are two places it can choose. The module maps one parent with two children three ways; T01_ShapesTest.java runs them and records the tables and the insert SQL.
@JoinColumn puts the key in the child table but costs an extra update per child; the bidirectional mapping writes the key in the child’s own insert. The diagram counts statements; the transcript below shows them.
The first block is the plain mapping (01-shapes-h7.txt):
tables: [JTCHILD, JTLISTPARENT, JTLISTPARENT_JTCHILD]
-- persist(parent with 2 children); commit
sql> insert into JtListParent (id) values (default)
sql> insert into JtChild (name,id) values (?,default)
sql> insert into JtChild (name,id) values (?,default)
sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?)
sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?)
Compare that with the bidirectional mapping from the same transcript, 01-shapes-h7.txt:
tables: [DEPARTMENTS, EMPLOYEES]
sql> insert into departments (name,id) values (?,default)
sql> insert into employees (dept_id,name,uuid,id) values (?,?,?,default)
sql> insert into employees (dept_id,name,uuid,id) values (?,?,?,default)
The rule of thumb that comes out of this. If the child has a back-reference to its parent, map it withmappedByand let the@ManyToOneown the column. You get two tables, no extra statements, and the removal behaviour in the next sections. The other shapes are legitimate when the child genuinely has no reason to know its parent, but you pay for it.
What the join table and the @JoinColumn variant each cost
With a join table, every child needs its owninsert into the link table on top of the child insert, and the @OneToMany field alone decides everything about that table: its name (JtListParent_JtChild here), its two columns, and its rows. That is why a join table List behaves so differently when you remove a child, which the fourth section measures.
With @JoinColumn on a unidirectional mapping there is no link table, but Hibernate inserts the child first (without the key, because the child has no field to carry it) and then sends one update ... set parent_id=? per child. The transcript above shows both updates in block B of 01-shapes-h7.txt.
- Variants.java holds every mapping variant as small nested entities (
Jt*,Jc*,Oc*,Bi*) - T01_ShapesTest.java, the test that wrote the transcript above
- JPA cascade types in Hibernate 7, for what
cascadeandorphanRemovaldo on top of these mappings
Bidirectional means you must update both sides yourself
Hibernate does not keep the two Java fields in step for you. If you add an employee todepartment.getEmployees() and forget to set employee.setDepartment(department), the owning field is still null, and the owning field is the one that gets written. The T03_SyncHelperTest.java test does exactly that, then does it again through a helper method, and reads the column back with raw JDBC:
in memory, before flush: e.department == null
database after commit: employee 1 has dept_id = null
database after commit: employee 2 (via helper) has dept_id = 2
The fingerprint of a missing sync. Rows exist, the code ran without an error, andThe fix is to never touch the collection directly. Put the two-sided update in one method on the parent, as Department.java does:dept_idisnull. The employee is simply not in any department as far as the database is concerned. Nothing fails; the data is just wrong.
// The invariant that keeps both sides of the association in step.
public void addEmployee(Employee employee) {
employees.add(employee);
employee.setDepartment(this);
}
public void removeEmployee(Employee employee) {
employees.remove(employee);
employee.setDepartment(null);
}
Going deeper
List or Set: what removing one child really costs
Removing a child from a collection is where the mapping you chose either does the obvious thing or does something expensive. T02_BagVsSetTest.java builds a parent with 5 children, then with 50, removes exactly one, flushes, and counts the write statements Hibernate sends. It does this for six mappings. AList without an @OrderColumn is what Hibernate calls a bag: an unordered collection that allows duplicates.
List or Set: a List on a bidirectional mappedBy mapping is as cheap as a Set.
Here is the worst bar, the unidirectional join-table List with 5 children, exactly as 02-bag-vs-set-h7.txt recorded it:
-- join table, List, n=5
sql> select jlp1_0.id from JtListParent jlp1_0 where jlp1_0.id=?
sql> select c1_0.JtListParent_id,c1_1.id,c1_1.name from JtListParent_JtChild c1_0 join JtChild c1_1 on c1_1.id=c1_0.children_id where c1_0.JtListParent_id=?
sql> delete from JtListParent_JtChild where JtListParent_id=?
sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?)
sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?)
sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?)
sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?)
sql> delete from JtChild where id=?
Hibernate deleted every row of the link table for this parent, then re-inserted the four that survive, then deleted the one orphan. The same removal in a bidirectional mapping is one statement (same transcript, 02-bag-vs-set-h7.txt):
-- bidirectional, Set, n=5
sql> select d1_0.id,d1_0.name from departments d1_0 where d1_0.id=?
sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=?
sql> delete from employees where id=?
This corrects the usual advice. The old version of this article, like many others, said that removing one child from anyListdeletes all the children and re-inserts the rest. The run shows that is only true for a unidirectional join-table bag. AListon amappedBymapping sent onedelete, and a@JoinColumnListsent oneupdateplus onedelete. And what gets deleted and re-inserted is the link-table rows, not the children themselves.
Why a join-table bag rewrites everything (my reading, not a measurement)
A bag has no position and no per-element key, so a row in the link table cannot be pointed at individually. Hibernate’s only safe move is to clear the parent’s rows and write back what remains. I am stating that as the explanation that fits the SQL above, not as something the tests prove; what the tests prove is the statement counts. TheSet mapping can send delete from JtSetParent_JtChild where JtSetParent_id=? and children_id=? because each element is its own identity.
@OrderColumn: an ordered list is not free
Adding@OrderColumn gives the list a position column so Hibernate can address elements, but it must keep the numbers contiguous. Removing the first of 5 children sent 9 update statements and 1 delete; removing the first of 50 sent 99 updates (2n−1). Removing the first element is the worst case I measured; I did not measure removing the last. The whole transcript is 02-bag-vs-set-h7.txt.
- T02_BagVsSetTest.java and its full transcript
- Variants.java, the six mappings compared
- Hibernate 7 many-to-many, where the same
Setcontract applies
A Set is only as good as the child’s hashCode
ChoosingSet has a condition attached. A HashSet files each element under its hashCode() at the moment you add it. If that value changes afterwards, the set can no longer find the element. An entity whose hashCode is built from its database id has exactly that problem: the id is null when you add the child, and persist() assigns it. T06_IdHashCodeTest.java puts the two designs side by side:
id-based hashCode: Set.remove(child) returned false
rows left in IdHashChild: 1 (the child was NOT removed, so orphanRemoval never saw it)
UUID-based hashCode: Set.remove(child) returned true
rows left in employees: 0
The id-based child could not be removed from its own parent’s set, so orphanRemoval never saw the removal and the row stayed. The fix is in Employee.java: a UUID assigned at construction that never changes.
@Override
public boolean equals(Object o) {
return o instanceof Employee e && Objects.equals(uuid, e.uuid);
}
@Override
public int hashCode() {
return Objects.hashCode(uuid);
}
A silent failure. Nothing throws whenGoing deeperSet.remove()returnsfalse. Your service thinks the child is gone, the database disagrees, and the row survives until someone notices it.
- T06_IdHashCodeTest.java
- Variants.java (
IdHashChildis the deliberately broken one)
Which side loads what: the fetch defaults
JPA gives the two sides different defaults, and they surprise people in opposite directions.@OneToMany is LAZY: the collection is not read until you touch it. @ManyToOne is EAGER: the parent is read together with the child. T04_FetchTest.java leaves both at the default in EagerEmployee.java and EagerDepartment.java:
-- find(EagerEmployee) with @ManyToOne at its default
sql> select ee1_0.id,d1_0.id,d1_0.name,ee1_0.name from EagerEmployee ee1_0 left join EagerDepartment d1_0 on d1_0.id=ee1_0.dept_id where ee1_0.id=?
-- find(EagerDepartment): the @OneToMany collection is not loaded
sql> select ed1_0.id,ed1_0.name from EagerDepartment ed1_0 where ed1_0.id=?
Loading an employee brought the department along in the same statement through a left join. Loading a department did not touch the employees table at all. That is why the module’s Employee.java sets fetch = FetchType.LAZY explicitly on the @ManyToOne.
A claim from the old article that the run does not support. The earlier text warned that an eagerGoing deeper@ManyToOne“might then trigger a load of all other Employees in that department”. It did not: one statement, one department row, the collection stayed lazy. The real cost of an eager@ManyToOneis the extra join or extra select you pay on every child load, whether you need the parent or not.
Lazy collections cause N+1, and two ways out
A lazy collection is read the first time you touch it. Load five departments and loop over their employees, and Hibernate sends one query for the departments and one more for each department: that is the N+1 problem. The test loads 5 departments with 3 employees each and counts statements three ways (05-n-plus-one-h7.txt). The naive loop sends the same per-departmentselect five times; the block shows it once:
-- naive: query departments, then touch each employees collection
sql> select d1_0.id,d1_0.name from departments d1_0
sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=?
-- fix 1: left join fetch d.employees
sql> select d1_0.id,e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid,d1_0.name from departments d1_0 left join employees e1_0 on d1_0.id=e1_0.dept_id
-- fix 2: @BatchSize(size = 20) on the collection, same loop as the naive one
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 in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
| Approach | Statements for 5 departments | Where it is set |
|---|---|---|
| Naive loop over a lazy collection | 6 (1 + 5) | nowhere, it is the default |
left join fetch d.employees | 1 | the query |
@BatchSize(size = 20) | 2 | the collection mapping |
@BatchSize keeps the collection lazy but loads it for up to 20 parents at a time using an IN list. On 7.4.16 the join fetch above returned 5 departments, not 15, so no distinct was needed.
When to use which fix
| Situation | Reach for |
|---|---|
| You always need the children for this query | join fetch |
| You sometimes need them, and the parent list can be long | @BatchSize |
| You need two collections at once | see the next section: Set, two queries, or @BatchSize |
? placeholders even though only five parents were loaded. Hibernate pads the IN list to the batch size. I confirmed the padding in the transcript but did not investigate how it chooses the sizes for other counts.
- T04_FetchTest.java, the test behind both fetch sections
- output/05-n-plus-one-h7.txt
MultipleBagFetchException and its three fixes
Give a department twoList collections, say employees and projects, and join-fetch both in one query. Hibernate refuses. T05_MultipleBagTest.java runs it and captures the exception:
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)
Notice that no SQL was sent: the query is rejected while it is being built. The exception says “bags” because a List without @OrderColumn is a bag, and Hibernate will not fetch two bags in one query. The reason is the shape of the result, which the next diagram shows.
Set the query is allowed, and the transcript confirms the 12 rows for 3 + 4 objects. The usual explanation, and the one the original article gave, is that with bags Hibernate cannot reliably tell which duplicate rows are real and which are artefacts of the multiplication, so it stops you. The tests prove the refusal, not that reasoning.
Fix 1 is a Set. One query, two join fetches, 12 rows, correct result (06-multiple-bag-h7.txt):
== 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 2 keeps the Lists and splits the work into two queries, one collection each (same transcript, 06-multiple-bag-h7.txt):
== Fix 2: split into two queries (same Lists)
-- 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 3 keeps the Lists, drops the join fetch, and lets @BatchSize load each collection lazily (same transcript, 06-multiple-bag-h7.txt):
== Fix 3: keep Lists, drop the join fetch, add @BatchSize
-- 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=?
Choosing between the three fixes
| Fix | Statements (1 department) | Rows transferred | Catch |
|---|---|---|---|
Set + two join fetches | 1 | 3 x 4 = 12 | rows grow as the product of the two collection sizes; needs a sound hashCode |
| Two queries | 2 | 3 + 4 = 7 (plus parent columns repeated) | you write and order the queries yourself |
@BatchSize | 3 (parents, employees, projects) | 3 + 4 | collections load lazily, so you need an open session |
- T05_MultipleBagTest.java
- output/06-multiple-bag-h7.txt
- Mastering lazy loading in Hibernate 7, for entity graphs as another way to choose what loads
Should you map the collection at all?
Everything above is about mapping a collection that belongs to the parent. Whether to have that collection is a separate decision. Loading it is a plainselect ... where dept_id=? with no limit, as every transcript here shows, so a department with 20,000 employees loads 20,000 objects the first time you touch getEmployees().
Honest advice. Map@OneToManywhen the children are a small, bounded part of the parent (order lines, an invoice’s items) and you usually work with all of them at once. When the collection can grow without bound, keep only the@ManyToOneon the child and query children by parent with a paged repository method. You give updepartment.getEmployees()and keep a model that cannot accidentally load the whole table. I did not benchmark memory or dirty-checking cost for large collections; this advice rests on the unboundedselectvisible above.
More pitfalls (not run in the companion module)
These two came from the original article and are widely documented, but the companion module does not exercise them, so treat them as advice rather than measured fact.- Lombok
@Dataon entities. It generatestoString(),equals()andhashCode()over every field, including lazy collections. That can trigger lazy loading from a log line and runs straight into the hashCode problem from the fifth section. - JSON serialization of both sides. A bidirectional association serializes as an endless loop unless you break it, for example with
@JsonBackReferenceon the child or by returning DTOs.
Frequently asked questions
Is @OneToMany lazy by default?
Yes, it always has been. @ManyToOne and @OneToOne default to eager. The fetch-defaults section shows both in SQL.
When should I avoid @OneToMany for a large collection?
When the collection is unbounded. Touching it loads every child, as the SQL above shows. Use a paged query on the child instead; the last section explains the trade.
When should I use @BatchSize instead of JOIN FETCH?
When you need more than one collection, or when the join would repeat a lot of parent data. The N+1 and bag sections show the statement counts for each.
What does Hibernate 7 change for these mappings?
Everything on this page was run on 7.4.16.Final and none of it needed a Hibernate-7-specific API; the annotations are the standard Jakarta Persistence ones. The N+1 section shows one thing worth knowing on 7.4.16: a join fetch of a collection returned each parent once, with no distinct. The original article also credited Hibernate 7 with other mapping improvements; I could not verify those with a test, so they are not repeated here.
What is the difference between CascadeType.ALL and orphanRemoval = true?CascadeType.ALL passes persist, merge, remove, refresh and detach from the parent to its children. orphanRemoval = true is separate: it deletes a child when it is removed from the parent’s collection, even though nobody called remove() on the child. REMOVE only fires when the parent is deleted. The mappings in this module combine both, and the removal transcripts above show orphanRemoval producing the delete statements. The cascade module of the same repository covers the differences in depth: JPA cascade types in Hibernate 7.
Takeaways. Map it bidirectionally withmappedBy, set@ManyToOnetoLAZY, update both sides through a helper on the parent, give children a stablehashCode, and pick the loading strategy per query. Choose aSetor amappedByList; avoid the unidirectional join-tableListfor anything that changes. Run the module and read the SQL yourself: it is faster than trusting any article, this one included.
Further reading
- hibernate-demo/one-to-many, the companion module with every test and transcript from this page
- Hibernate 7 association mappings, all four association types in one guide
- Hibernate 7 many-to-many, explicit join entities and the
Setcontract - JPA cascade types in Hibernate 7, the complete cascade reference
- Mastering lazy loading in Hibernate 7,
FetchType,JOIN FETCHand entity graphs - Hibernate 7 User Guide: one-to-many
No Comments yet!