Scrivio Interview library
DebuggingFoundations5 min read · updated 12 November 2026

A developer adds a line with order.getLines().add(line) but never calls line.setOrder(order). After commit, the order_id column of the new line is null. Why?

In a bidirectional association, Hibernate writes the foreign key only from the owning side, the side without mappedBy, which here is OrderLine.order. The developer changed only the inverse side, the mappedBy collection on Order, which Hibernate ignores for the foreign key. The cascade on the collection still inserts the line, but with order_id null. The fix is to always set both sides, ideally through helper methods on the parent such as addLine().

Why this question is asked

This bug is common because the Java code looks right: the line is in the order's list, and the line even appears in the database after commit. Only the foreign key is missing, so the line is orphaned and silently disappears from the order the next time it is loaded. Interviewers ask about it because it tests the single most important rule of bidirectional mappings. In this answer, we will recap the owning side and mappedBy, reproduce the bug step by step, explain why Hibernate behaves this way, fix it with helper methods, and add a database constraint that turns the silent bug into a loud one.

1A Quick Recap: Owning Side and mappedBy

A bidirectional one-to-many has two Java references, Order.lines and OrderLine.order, but only one database column, order_line.order_id. JPA must know which Java reference to read when it writes that column. The one it reads is called the owning side. In a one-to-many, the owning side is always the many side, because that is where the foreign key lives.

The other side declares mappedBy = "order". That attribute literally says: this collection is a mirror of the field order on OrderLine, so do not use me to write anything. The inverse side is there for our convenience when navigating in Java, nothing more.

2Reproducing the Bug

Here is the mapping and the code from the question.

Java
@Entity class Order {
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
List<OrderLine> lines = new ArrayList<>();
}
@Entity class OrderLine {
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "order_id")
Order order;
}
@Transactional
void addLine(long orderId) {
Order order = em.find(Order.class, orderId);
OrderLine line = new OrderLine("PEN-7", 3);
order.getLines().add(line); // inverse side only
// line.setOrder(order) never called
}
// at commit:
// insert into order_line (order_id, quantity, sku, id) values (null, 3, 'PEN-7', 51)
Step throughWhich side Hibernate reads at flush
CodeOrder.lines (inverse)OrderLine.order (owner)Hibernate
lines.add(line)
cascade: find new line, persist it
read order -> null
insert order_line with order_id = null
next load: line is not in order.lines

5 messages in order. Play them, or step through them one at a time.

The collection triggers the cascade, but the foreign key comes only from the owner.

Notice what happened. Cascade ALL on the collection made Hibernate notice the new line and persist it, which is why the row exists. But when Hibernate built the insert, it read line.order to fill order_id, found null, and wrote null. The add to the list itself was never translated into SQL, because the list is the mapped-by side.

3Why Hibernate Ignores the Inverse Side

It might seem friendlier if Hibernate looked at both sides. The reason it does not is that the two sides can disagree, and Hibernate needs a single source of truth. Imagine code that adds a line to order A's collection while the line's order field says order B. Which one should win? JPA settles it once: the owning side wins, always. That keeps flush deterministic and avoids writing the same column twice.

So the inverse side is used for reading (loading order.getLines() runs a query on order_id) and for cascading, but never for writing the foreign key. Keeping the two in step in memory is our job.

4Fix: Set Both Sides Through a Helper

The reliable fix is to put the two assignments into one method on the parent, and to make that method the only way to add a line.

Java
@Entity class Order {
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderLine> lines = new ArrayList<>();
public void addLine(OrderLine line) {
lines.add(line);
line.setOrder(this); // owning side: this is what Hibernate writes
}
public List<OrderLine> getLines() { return Collections.unmodifiableList(lines); }
}
order.addLine(new OrderLine("PEN-7", 3));
// insert into order_line (order_id, quantity, sku, id) values (12, 3, 'PEN-7', 52)

Returning an unmodifiable view from getLines() means order.getLines().add(line) now throws UnsupportedOperationException, so the old pattern cannot creep back in. Setting only the owning side would also write the correct foreign key, but then the in-memory collection would miss the line for the rest of the transaction, which breaks code such as totals computed from order.getLines().

5Making the Silent Bug Loud

The worst part of this bug is that nothing fails: the row is saved, and the line simply vanishes from the order. We should let the database refuse it. Declaring the column NOT NULL in the schema, and @ManyToOne(optional = false) with @JoinColumn(nullable = false) in the mapping, turns the bug into an immediate exception at flush. A line without an order is meaningless anyway, so the constraint documents the rule as well as enforcing it.

SQL
ALTER TABLE order_line ALTER COLUMN order_id SET NOT NULL;
-- the buggy code now fails at flush:
-- ERROR: null value in column "order_id" of relation "order_line" violates not-null constraint

6Follow-up questions

Would it work if the collection were the owning side?

Only in a unidirectional @OneToMany with @JoinColumn, where there is no mappedBy and the collection owns the column. In that mapping Hibernate writes order_id from the collection, often with an extra update. In a bidirectional mapping, the many side should own it.

Does the same rule apply to @ManyToMany?

Yes. Only the side without mappedBy writes the link table. Adding to the inverse collection alone writes no link row at all, so helper methods should update both collections.

Why does the line not appear in order.getLines() after a reload?

Because loading the collection runs a query for order_line rows where order_id equals the order's id, and this row has null. The row exists but belongs to no order.

7Conclusion

In this answer, we saw that the null order_id comes from changing only the inverse side of a bidirectional association. Hibernate writes the foreign key from the owning side, OrderLine.order, and ignores the mappedBy collection for it, while the cascade still inserts the line. We fixed it with an addLine() helper that sets both sides and an unmodifiable getter, and made similar bugs fail loudly with a NOT NULL constraint and a non-optional mapping.

What to say in the interviewAbout 80 seconds aloud

Open with

In a bidirectional association, only the owning side is used to write the foreign key, and the owning side is the one without mappedBy, here OrderLine.order, because the foreign key column lives in order_line.

Then, if they want more

The collection on Order is the inverse side; mappedBy tells Hibernate it's just a mirror, so changes made only to it are ignored when writing the column.

What happened is that the developer added the line to the collection, the cascade on that collection made Hibernate persist the new line, but when it built the insert it read line.order, which was null, and wrote order_id as null. So the row exists but belongs to no order, and it disappears the next time the order is loaded.

Hibernate does it this way so there's one source of truth when the two sides disagree. The fix is to always set both sides, and I'd enforce that with helper methods on Order: addLine adds to the list and calls line.setOrder(this), removeLine does the reverse, and getLines returns an unmodifiable view so nobody can bypass them.

I'd also make order_id NOT NULL in the database and the ManyToOne non-optional, so if someone makes the same mistake again, it fails at flush instead of silently losing data.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A developer adds a line with order.getLines().add(line) but never calls...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/e38548be52/