Member-only story
Why You Should Avoid the Unidirectional @OneToMany Association in JPA
When designing a database schema in JPA, relationships between entities play a crucial role in ensuring performance, maintainability, and readability. A common decision is how to model a one-to-many relationship. While a unidirectional @OneToMany
association may seem like a straightforward approach, it can lead to significant inefficiencies compared to its bidirectional counterpart.
Here we explore the drawbacks of unidirectional @OneToMany
associations, particularly focusing on performance penalties during database operations.
Let’s consider the example of Company
and Employee
entities:
- A
Company
can have multipleEmployee
(one-to-many). - Each
Employee
is associated with a singleCompany
(many-to-one).
Unidirectional
//Now, let’s assume that the Company and Employee entities are involved in a unidirectional @OneToMany association mapped, as follows:
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();
Bidirectional
public class Company {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employees= new ArrayList<>();
}
public class Employee {
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;
}
//Reference is mentioned in both the classes