Wednesday, 5 December 2018

Many to Many Annotation


  1. 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.
  2. 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.
  3. The model classes Employee and Project need to be created with JPA annotations:
    1. @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 }
  4. Both the Employee class and Project classes refer to one another, which means that the association between them is bidirectional.
  5. In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations. 
  6. @ManyToMany
    1. The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.
  7. @JoinTable
    1.  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
  8. @JoinColumn
    1. 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
  9. mappedBy
    1. 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


No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *