Member-only story

Why You Should Avoid the Unidirectional @OneToMany Association in JPA

Namrata
4 min readDec 6, 2024

--

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 Companycan have multiple Employee(one-to-many).
  • Each Employeeis associated with a single Company(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

--

--

Namrata
Namrata

Written by Namrata

Engineering @Microsoft A software developer writing her daily bits . https://www.linkedin.com/in/namrataagarwal5/

No responses yet