Skip to main content

@OneToMany in Hibernate 7: Unidirectional vs Bidirectional, Set vs List and the SQL

What a Hibernate 7 @OneToMany really sends to the database: unidirectional join table vs @JoinColumn vs bidirectional mappedBy, what removing one child costs for List and Set, the sync helper, fetch defaults, N+1 and MultipleBagFetchException, all with real SQL from a runnable companion module.

You added @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 ORM 7.4.16.Final (the newest 7.x GA listed in maven-metadata.xml on 2026-11-16; 8.0.0.CR1 is listed after it but is a candidate release and was not tested), Jakarta Persistence 3.2.0, H2 2.4.240, JUnit 6.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: an employees 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.
Java classes Department Set<Employee> employees @OneToMany(mappedBy = “department”) the inverse side: Hibernate never writes from here Employee Department department @ManyToOne @JoinColumn(name = “dept_id”) the owning side: this field becomes dept_id mappedBy Database tables departments id | name employees id | name | uuid | dept_id dept_id → id The collection on Department is a view of the employees rows. The foreign key column belongs to the child table, and the Employee.department field is what Hibernate reads when it writes that column.
The diagram is the whole mental model. The two Java fields at the top map onto one column at the bottom, and only the 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. Touch department.getEmployees() after the transaction has ended and you get LazyInitializationException. Put @Transactional on 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 the jakarta.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.
Going deeper

The same relationship mapped three ways sends different SQL

You can write a one-to-many without mappedBy, 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.
A. plain @OneToMany JtListParent JtChild JtListParent_JtChild a third table you did not ask for 1 insert parent 2 inserts child 2 inserts join rows = 5 B. @JoinColumn JcListParent JcChild FK parent_id lives in JcChild 1 insert parent 2 inserts child 2 UPDATEs to set parent_id = 5 C. bidirectional departments employees FK dept_id lives in employees 1 insert parent 2 inserts child, FK included = 3 Same job, same data: one parent, two children. The mapping alone changes the tables and the statement count. Statements are counted from the committed transcript in output/01-shapes-h7.txt.
The plain unidirectional mapping creates a join table; adding @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 with mappedBy and let the @ManyToOne own 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 own insert 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.
Going deeper

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 to department.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, and dept_id is null. The employee is simply not in any department as far as the database is concerned. Nothing fails; the data is just wrong.
The fix is to never touch the collection directly. Put the two-sided update in one method on the parent, as Department.java does:
	// 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. A List without an @OrderColumn is what Hibernate calls a bag: an unordered collection that allows duplicates.
Write statements to remove ONE child from 50 @JoinColumn + @OrderColumn100 join table, List (bag)51 join table, Set2 @JoinColumn, List2 bidirectional mappedBy, List1 bidirectional mappedBy, Set1 The two long bars grow with the collection (51 and 100 here; 6 and 10 for five children). The rest stay flat. Counts come from output/02-bag-vs-set-h7.txt. Bar length is proportional to the count.
Two bars grow with the collection and four do not. Which mapping you have matters more than whether you wrote 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 any List deletes all the children and re-inserts the rest. The run shows that is only true for a unidirectional join-table bag. A List on a mappedBy mapping sent one delete, and a @JoinColumn List sent one update plus one delete. 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. The Set 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.
Going deeper

A Set is only as good as the child’s hashCode

Choosing Set 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 when Set.remove() returns false. Your service thinks the child is gone, the database disagrees, and the row survives until someone notices it.
Going deeper

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 eager @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 @ManyToOne is the extra join or extra select you pay on every child load, whether you need the parent or not.
Going deeper

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-department select 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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ApproachStatements for 5 departmentsWhere it is set
Naive loop over a lazy collection6 (1 + 5)nowhere, it is the default
left join fetch d.employees1the query
@BatchSize(size = 20)2the collection mapping
Join fetch is the right tool when you know up front that you need the children. @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
SituationReach for
You always need the children for this queryjoin fetch
You sometimes need them, and the parent list can be long@BatchSize
You need two collections at oncesee the next section: Set, two queries, or @BatchSize
The batch statement above has twenty ? 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.
Going deeper

MultipleBagFetchException and its three fixes

Give a department two List 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.
One department, 3 employees, 4 projects, two join fetches p0p1p2p3 e0e1e2 12 rows come back one per (employee, project) pair, although the data is only 3 + 4 objects. Hibernate folds the rows back into two collections. The cost is paid in rows transferred: 30 x 40 would be 1,200. The 12 is measured in output/06-multiple-bag-h7.txt. The 1,200 is arithmetic, not a measurement.
Two join fetches multiply the rows. With a 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
FixStatements (1 department)Rows transferredCatch
Set + two join fetches13 x 4 = 12rows grow as the product of the two collection sizes; needs a sound hashCode
Two queries23 + 4 = 7 (plus parent columns repeated)you write and order the queries yourself
@BatchSize3 (parents, employees, projects)3 + 4collections load lazily, so you need an open session
The “rows transferred” column for fixes 2 and 3 is reasoning from the SQL shown, not a separate measurement. The statement counts are asserted by T05_MultipleBagTest.java.
Going deeper

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 plain select ... 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 @OneToMany when 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 @ManyToOne on the child and query children by parent with a paged repository method. You give up department.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 unbounded select visible 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 @Data on entities. It generates toString(), equals() and hashCode() 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 @JsonBackReference on 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 with mappedBy, set @ManyToOne to LAZY, update both sides through a helper on the parent, give children a stable hashCode, and pick the loading strategy per query. Choose a Set or a mappedBy List; avoid the unidirectional join-table List for anything that changes. Run the module and read the SQL yourself: it is faster than trusting any article, this one included.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.