One-to-many and the owning side
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
map the collection side and know who owns the relationship.
Planned topics
@OneToMany(mappedBy = "order")is the inverse side: it shows the children but does not write the foreign key.- The side with
@JoinColumn(the many-to-one) is the owning side; only its value is saved. - Keep both sides in sync with helper methods (
addLine,removeLine). - Initialize collections (
new ArrayList<>()) and expose them carefully. - Forgetting to set the owning side saves a
nullforeign key.
Draft outline details
Demonstration
@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
}Check your understanding
Which side's value is written to the foreign key column?
Show answer
The owning side, the one without mappedBy.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.