Video in progress
How do you write a bidirectional association with @OneToMany and @ManyToOne, and why is mappedBy needed?
The foreign key lives in the child table, so the @ManyToOne side is the owning side. On the parent side you write @OneToMany(mappedBy = "..."), which tells Hibernate "this association is managed through that field; don't create a separate column or table."
📖 Answer
Here is the full picture with a department and its employees:
@Entity
public class Department {
@Id @GeneratedValue
private Long id;
@OneToMany(mappedBy = "department")
private List<Employee> employees = new ArrayList<>();
}
@Entity
public class Employee {
@Id @GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
}
The value of mappedBy is the field name in the child class (department), not a column name.
If you forget mappedBy, Hibernate treats them as two independent associations and tries to create an extra join table for the @OneToMany (department_employees). With Flyway this shows up as a "table not found" error; with ddl-auto=update an extra table quietly appears.
Initialize the collection right in the field with new ArrayList<>(), so it isn't null on a new object.
Sign up to mark studied questions and save your progress.