Is there a way to optimize ManyToOne relationships using JPA?
P粉609866533
P粉609866533 2024-01-29 13:09:59
0
1
451

I have an employee who works in multiple departments. I have OneToMany relationship in Employee and ManyToOne in 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 table created in MySQL is as follows:

  • Employee table:
  • Department table:

The problem is that I will have multiple employees and they can have multiple departments. The department table will be too big and the department names will be repeated for different employees as shown in the above image I have 2xManagement. My question is if it is possible to create department table without employee_id (only with department name) and link in a separate table with only two attributes (employee_id and department_id). Do I need to create a new class for this? How can I optimize this relationship? Is there a way to do it?

P粉609866533
P粉609866533

reply all(1)
P粉391955763

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template