Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Map a bidirectional Order to OrderLine relationship correctly, and write helper methods that keep both sides in sync.

OrderLine owns the relationship with @ManyToOne(fetch = FetchType.LAZY) and @JoinColumn(name = "order_id"), because the foreign key lives in its table. Order has the inverse side, @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) on a List initialised to an empty ArrayList. Helper methods addLine() and removeLine() on Order change the collection and the line's order reference together, so both sides of the Java object graph always agree with what Hibernate writes.

Why this question is asked

Order and its lines are the textbook parent-child relationship, and nearly every business application has one. Getting the mapping slightly wrong produces bugs that are hard to see: foreign keys left null, extra update statements, or lines that are not deleted when removed from the order. Interviewers ask for this mapping and its helper methods because it shows whether we understand which side of the relationship Hibernate actually uses. In this answer, we will recap owning and inverse sides, map both entities, write the helper methods, see what goes wrong without them, and look at the SQL Hibernate produces.

1A Quick Recap: Two Sides, One Foreign Key

In the database there is only one thing: an order_id column in the order_line table pointing to the order. In Java we want two things: an Order that knows its lines, and an OrderLine that knows its order. A bidirectional association maps both Java references onto that single column.

JPA needs to know which reference to read when it writes the column. That side is called the owning side. The rule is simple: the owning side is the one with the foreign key, which in a one-to-many is always the many side, OrderLine. The other side, Order.lines, is the inverse side, and it says so with mappedBy, which names the field on the owning side that it mirrors.

2Mapping the Owning Side: OrderLine

The line holds the @ManyToOne. We set the fetch type to LAZY explicitly, because JPA's default for @ManyToOne (and @OneToOne) is EAGER, which would load the order every time any line is loaded.

Java
@Entity
@Table(name = "order_line")
public class OrderLine {
@Id @GeneratedValue private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "order_id") // the foreign key column in order_line
private Order order;
private String sku;
private int quantity;
protected OrderLine() { }
public OrderLine(String sku, int quantity) { this.sku = sku; this.quantity = quantity; }
void setOrder(Order order) { this.order = order; } // package-private: only Order calls it
public Order getOrder() { return order; }
}

Notice that setOrder is package-private. We want code outside the domain package to go through the Order's helper methods, which keep both sides in step, rather than setting one side and forgetting the other.

3Mapping the Inverse Side and the Helpers: Order

The order holds the collection. mappedBy = "order" points to the field name in OrderLine. Cascade ALL means persisting or removing an order does the same to its lines, and orphanRemoval = true means a line removed from the collection is deleted, which suits lines that cannot exist without their order. The list is initialised so it is never null on a new order.

Java
@Entity
@Table(name = "orders") // ORDER is a reserved word in SQL
public class Order {
@Id @GeneratedValue private Long id;
@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);
}
public void removeLine(OrderLine line) {
lines.remove(line);
line.setOrder(null);
}
public List<OrderLine> getLines() { return Collections.unmodifiableList(lines); }
}

The getter returns an unmodifiable view, so callers cannot do order.getLines().add(line) and bypass the helper. Hibernate does not use this getter when we map with field access (the @Id is on a field), so returning a view is safe.

One detail about removeLine: List.remove(Object) relies on equals(). If OrderLine does not override equals, identity is used, which is fine as long as we pass the same instance that is in the list, as is usual inside one persistence context.

4Seeing the SQL

With the helpers in place, creating an order with two lines is one call to save, and Hibernate inserts the parent first and then the children with the foreign key already filled.

Java
Order o = new Order();
o.addLine(new OrderLine("BOOK-1", 2));
o.addLine(new OrderLine("PEN-7", 10));
orderRepository.save(o);
// insert into orders (id) values (1)
// insert into order_line (order_id, quantity, sku, id) values (1, 2, 'BOOK-1', 1)
// insert into order_line (order_id, quantity, sku, id) values (1, 10, 'PEN-7', 2)
o.removeLine(o.getLines().get(1)); // inside a transaction
// at flush: delete from order_line where id = 2 (orphanRemoval)
Step throughaddLine keeps both sides in step
ServiceOrderOrderLineHibernate
addLine(line)
lines.add(line)
setOrder(this)
save(order)
cascade PERSIST to lines
read line.order -> order_id = 1

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

Hibernate reads the owning side, line.order, to fill the foreign key.

Notice there is no update statement after the inserts. Because the owning side, line.order, was set before the insert, Hibernate writes order_id in the insert itself. That is a direct benefit of the bidirectional mapping with the many side as owner.

5What Goes Wrong Without the Helpers

If code only adds the line to the collection, the Java graph looks right, the cascade persists the line, but the owning side is null, so Hibernate inserts order_id as null (or fails on a NOT NULL constraint, which optional = false and a non-null column give us). If code only sets line.setOrder(order) without adding to the list, the database is right, but the in-memory order does not show the new line until it is reloaded, which leads to confusing bugs within the same transaction, such as a total that ignores the new line. The helpers make the right thing the only thing.

6Follow-up questions

Why not use Set instead of List for the lines?

Either works for a mappedBy one-to-many. A List keeps insertion order in memory and allows duplicates; a Set needs a careful equals and hashCode on OrderLine, because the id is null before persist. Lines are often fine as a List; the bag problems with List mostly affect @ManyToMany and multiple join fetches.

Should equals and hashCode on OrderLine use the id?

If they do, they must handle the null id of a new line, typically by comparing ids only when both are set and returning a constant hashCode for the class. A business key, such as order plus line number, is another stable option.

Is cascade ALL always right for a one-to-many?

Only when the parent owns the children's whole life, as with order lines. For a reference to independent entities, such as orders of a customer, cascading remove would be dangerous and is not used.

7Conclusion

In this answer, we mapped a bidirectional Order to OrderLine relationship. OrderLine is the owning side, with a LAZY @ManyToOne and @JoinColumn(name = "order_id"), because the many side holds the foreign key and @ManyToOne is EAGER by default. Order is the inverse side, with mappedBy, cascade ALL and orphanRemoval on an initialised list. The addLine() and removeLine() helpers update both sides together, which lets Hibernate write the foreign key in the insert and keeps the in-memory graph consistent.

What to say in the interviewAbout 80 seconds aloud

Open with

The foreign key lives in the order_line table, so OrderLine is the owning side. I'd map it with @ManyToOne(fetch = LAZY) and @JoinColumn(name = "order_id"). I set LAZY explicitly because ManyToOne is EAGER by default in JPA.

Then, if they want more

On Order, I'd map the inverse side with @OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true) on a List initialised to a new ArrayList, since lines can't exist without their order.

Then I'd add two helper methods on Order. addLine adds the line to the list and calls line.setOrder(this); removeLine removes it from the list and sets the line's order to null.

The reason is that Hibernate only looks at the owning side to write the foreign key, so if someone only adds to the collection, the line is inserted with a null order_id, and if they only set the order, the in-memory collection is out of date.

I'd make the line's setOrder package-private and return an unmodifiable view of the lines, so everyone goes through the helpers. With that, saving an order inserts the order and then each line with order_id already set, no extra updates, and removing a line deletes it through orphanRemoval.

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 "Map a bidirectional Order to OrderLine relationship correctly, and write helper methods...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/6d85fe0065/