Skip to content
Ameen Abozaid
Planned lessonJNR-030-L02

One-to-many and the owning side

  • Lesson 2 of 8
  • Junior
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 null foreign key.
Draft outline details

Demonstration

java
@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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.