Video in progress

What is the owning side of an association and why does it matter?

The owning side is the side that determines which field sets the foreign key value. When Hibernate writes to the database, it looks only at that side. Changes on the inverse (mappedBy) side don't affect the database.

📖 Answer

Not knowing this rule causes a lot of "it didn't save" bugs:

Department d = em.find(Department.class, 1L);
Employee e = new Employee("Dilshod");

d.getEmployees().add(e);   // inverse side only
em.persist(e);
// result: employees.department_id = NULL

Hibernate takes department_id from e.getDepartment(), which is null. What you added to the collection exists only in Java memory.

The correct way:

e.setDepartment(d);          // owning side: this alone is enough to write to the database
d.getEmployees().add(e);     // so the in-memory state is correct too

Which side is the owner:

  • @ManyToOne: always the owner;
  • @OneToOne and @ManyToMany: the side without mappedBy;
  • @OneToMany without mappedBy: it becomes the owner, but that leads to a join table or extra UPDATEs.