Home > AI > Backend > SpringBoot > mysql-connector-java >

ManyToMany-Employee-Project

The relationship between employee and project is ManyToMany

Employee.java

@Data
@Entity
@Table(name = "employees")
public class Employee extends Parent {

    @Id
    @Column(name = "employee_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long employeeId;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(
            name = "employees_projects",
            joinColumns = {@JoinColumn(name = "employee_id")},
            inverseJoinColumns = {@JoinColumn(name = "project_id")}
    )
    Set<Project> projects = new HashSet<Project>();


}

Project.java

@Data
@Entity
@Table(name = "projects")
public class Project extends Parent{


    @Id
    @Column(name = "project_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long projectId;

    @Column(name = "title")
    private String title;

    @ManyToMany(mappedBy = "projects", cascade = {CascadeType.ALL})
    private Set<Employee> employees = new HashSet<Employee>();

}

EmployeeRepository.java

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

ProjectRepository.java

@Repository
public interface ProjectRepository extends JpaRepository<Project, Long> {

}

Leave a Reply