Home > other >  Is there any way to optimize ManyToOne Relationship using JPA?
Is there any way to optimize ManyToOne Relationship using JPA?

Time:03-27

I have an employee who can work in multiple departments. I have OneToMany relashionship in Employee and ManyToOne in the Department class.

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    
    @Size(min = 3, max = 10, message = "Invalid name")
    private String name;
    @Email
    private String email;
    
    @OneToMany(mappedBy = "employee")
    private List<Department> departments;
}

@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String department;
    
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "employee_id", referencedColumnName = "id")
    private Employee employee;
}

The created tables in MySQL looks like the following:

  • The employees table:

enter image description here

  • The departments table:

enter image description here

The problem is that I will have multiple employees and they can have multiple departments. The departments table will be too large and the departments name will be repeated for the different employees as you can see in the picture above I have 2xManagement. My question is if it is possible to create the departments table without the employee_id (only to have the departments name) and do the linking in a separate table with only two properties - employee_id and department_id. Do I need to create a new class for that? How can I optimize this relashionship? Is there a way to do it?

CodePudding user response:

You need change solution to @ManyToMany by using weak entity, References: https://www.baeldung.com/hibernate-many-to-many

  • Related