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
In a bidirectional lazy @OneToMany
association, JPA efficiently handles this relationship by keeping the foreign key column in the Employee
table. Operations like inserting or deleting a Employee
are simple: they require a single INSERT
or DELETE
operation directly in the Employee
table.
However, with a unidirectional @OneToMany
association, where Company
references Employee
without a corresponding @ManyToOne
mapping in Employee
, JPA introduces a junction table to manage the association. This junction table contains foreign keys pointing to both Company
and Employee
. While this design eliminates direct back-references, it comes with significant downsides.
