hibernate many-to-many

hibernate many-to-many

https://www.baeldung.com/hibernate-many-to-many

https://www.baeldung.com/jpa-many-to-many

knowledge

many-to-many relationship, both sides can relate to multiple instances of the other side.

Screen Shot 2020-11-24 at 11.15.51 PM

employee can be assigned to multiple projects and a project may have multiple employees working for it

  • An employee table with employee_id as its primary key
  • A project table with project_id as its primary key.
  • A join table employee_project is required here to connect both sides.

In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations.

The owning side is Employee so the join table is specified on the owning side by using the @JoinTable annotation in Employee class. The @JoinTable is used to define the join/link table. In this case, it is Employee_Project.

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.

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.


Practice

CREATE TABLE `employee` (
`employee_id` int NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB;

CREATE TABLE `project` (
`project_id` int NOT NULL AUTO_INCREMENT,
`title` varchar(50) DEFAULT NULL,
PRIMARY KEY (`project_id`)
) ENGINE=InnoDB;

CREATE TABLE `employee_project` (
`employee_id` int NOT NULL,
`project_id` int NOT NULL,
PRIMARY KEY (`employee_id`,`project_id`),
CONSTRAINT `employee_project_ibfk_1`
FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`),
CONSTRAINT `employee_project_ibfk_2`
FOREIGN KEY (`project_id`) REFERENCES `project` (`project_id`)
) ENGINE=InnoDB;