You use @OneToMany
without mappedBy
when you want to create a unidirectional one-to-many relationship where only the parent knows about the children, and you don’t want or can’t add a foreign key to the child table.
🔹 What happens technically?
- Without
mappedBy
, Hibernate has no “owning side” telling it which table contains the foreign key. - So it creates a join table linking the primary keys of both tables to represent the one-to-many association.
🔹 Example:
@Entity
public class Department {
@OneToMany // no mappedBy!
@JoinTable(
name = "department_employee",
joinColumns = @JoinColumn(name = "department_id"),
inverseJoinColumns = @JoinColumn(name = "employee_id")
)
private List<Employee> employees = new ArrayList<>();
}
🔹 What Hibernate does:
Creates a join table like:
department_employee
---------------------
department_id | employee_id
🔹 Why might you do this?
✅ You can’t or don’t want to modify the child table (e.g., Employee
table owned by another team or legacy system).
✅ You need a unidirectional relationship (only parent knows children), and your design doesn’t require the child to know the parent.
✅ You want to model something like a “basket of unrelated items”, where you just link existing rows without adding a foreign key in the item table.
🔹 What’s the downside?
❌ A join table adds complexity and indirection in the database → usually unnecessary if you can add a simple foreign key in the child table.
❌ Slightly less performant than a direct foreign key for one-to-many, especially with large datasets.
🔹 Comparison summary:
Approach | Behavior | DB Structure |
---|---|---|
@OneToMany(mappedBy=...) | Bidirectional, uses FK in child table | Direct foreign key |
@OneToMany without mappedBy | Unidirectional, uses join table | Extra join table linking both PKs |
✅ Key takeaway:
Use @OneToMany
without mappedBy
only when you want unidirectional relationships without modifying the child table, knowing that Hibernate will create a join table to maintain the association.