- In this scenario, any given employee can be assigned to multiple projects and a project may have multiple employees working for it, leading to a many-to-many association between the two.
- We have an employee table with employee_id as its primary key and a project table with project_id as its primary key. A join table employee_project is required here to connect both sides.
- The model classes Employee and Project need to be created with JPA annotations:
@Entity @Table(name = "Employee") public class Employee { // ... @ManyToMany(cascade = { CascadeType.ALL }) @JoinTable( name = "Employee_Project", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = { @JoinColumn(name = "project_id") } ) Set
projects = new HashSet<>(); // standard constructor/getters/setters } @Entity @Table(name = "Project") public class Project { // ... @ManyToMany(mappedBy = "projects") private Set employees = new HashSet<>(); // standard constructors/getters/setters } - Both the Employee class and Project classes refer to one another, which means that the association between them is bidirectional.
- In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations.
- @ManyToMany
- The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.
- @JoinTable
- In our example, the owning side is Employee so the join table is specified on the owning side by using the @JoinTable annotation in Employee class
- @JoinColumn
- The @JoinColumn annotation is used to specify the join/linking column with the main table. Here, the join column is employee_id and project_id is the inverse join column since Project is on the inverse side of the relationship
- mappedBy
- In the Project class, the mappedBy attribute is used in the @ManyToMany annotation to indicate that the employees collection is mapped by the projects collection of the owner side
Wednesday, 5 December 2018
Many to Many Annotation
About Unknown
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment