Home  >  Q&A  >  body text

Is there a way to optimize ManyToOne relationships using JPA?

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:

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粉609866533P粉609866533264 days ago378

reply all(1)I'll reply

  • P粉391955763

    P粉3919557632024-01-30 09:24:27

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

    reply
    0
  • Cancelreply