hibernate-013: Can You Mix Unidirectional and Bidirectional @OneToMany & @ManyToOne?
Hunor Vadasz-Perhat

Hunor Vadasz-Perhat @hunor85

About: Software Engineer II @DXC Technology

Location:
Denmark
Joined:
Jul 3, 2023

hibernate-013: Can You Mix Unidirectional and Bidirectional @OneToMany & @ManyToOne?

Publish Date: Feb 10
0 0

🚀 Can You Mix Unidirectional and Bidirectional @OneToMany & @ManyToOne?

Yes, you can! You can choose:

  • @ManyToOne without @OneToManyUnidirectional
  • @ManyToOne with @OneToMany(mappedBy)Bidirectional

📌 Mixing Unidirectional & Bidirectional Approaches

Scenario @ManyToOne Used? @OneToMany Used? Direction Type
Best Practice ✅ Yes ✅ Yes (mappedBy) Bidirectional
Alternative ✅ Yes ❌ No Unidirectional (@ManyToOne only)

1️⃣ Example: @ManyToOne Without @OneToMany (Unidirectional)

Best for queries from EmployeeDepartment but NOT the other way around.

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id") // ✅ Foreign key in Employee table
    private Department department;
}

@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}
Enter fullscreen mode Exit fullscreen mode

Queries:

  • employee.getDepartment(); (Works ✅)
  • department.getEmployees(); (Not possible ❌ - No @OneToMany)

🚀 Use case: If you only need to retrieve an employee's department, but NOT employees from a department.


2️⃣ Example: @ManyToOne + @OneToMany(mappedBy) (Bidirectional)

Best if you need queries in both directions.

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id") // ✅ Foreign key in Employee table
    private Department department;
}

@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "department") // ✅ Refers to Employee.department
    private List<Employee> employees;
}
Enter fullscreen mode Exit fullscreen mode

Queries:

  • employee.getDepartment(); (Works ✅)
  • department.getEmployees(); (Works ✅)

🚀 Use case: If you need to retrieve both:

  • All employees in a department
  • An employee’s department

🎯 Final Recommendation

When to Use Use @ManyToOne Only (Unidirectional) Use @ManyToOne + @OneToMany (Bidirectional)
Simple querying (best performance) ✅ Yes ❌ No
Only querying child → parent ✅ Yes ❌ No
Need parent → child queries ❌ No ✅ Yes
Avoiding unnecessary complexity ✅ Yes ❌ No

Best Practice:

  • Use @ManyToOne by itself (Unidirectional) if querying only from child → parent.
  • Use @ManyToOne + @OneToMany(mappedBy) (Bidirectional) if querying both ways.

Comments 0 total

    Add comment