Sunteți pe pagina 1din 9

5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

(/)

Hibernate Many to Many


Annotation Tutorial
Last modi ed: February 5, 2018

by Zeger Hendrikse (https://www.baeldung.com/author/zeger-author/)

Persistence (https://www.baeldung.com/category/persistence/)

I just announced the new Learn Spring course, focused on


the fundamentals of Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Introduction

In this quick tutorial, we’ll have a quick look at how the @ManyToMany
annotation can be used for specifying this type of relationships in Hibernate.

2. A Typical Example

Let’s start with a simple Entity Relationship Diagram – which shows the many-
to-many association between two entities employee and project:

https://www.baeldung.com/hibernate-many-to-many 1/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

(/wp-content/uploads/2017/09/New.png)
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.

3. Database Setup

Let’s assume we have an already created database with the name


spring_hibernate_many_to_many.
We also need to create the employee and project tables along with the
employee_project join table with employee_id and project_id as foreign keys:

https://www.baeldung.com/hibernate-many-to-many 2/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

1 CREATE TABLE `employee` (


2   `employee_id` int(11) NOT NULL AUTO_INCREMENT,
3   `first_name` varchar(50) DEFAULT NULL,
4   `last_name` varchar(50) DEFAULT NULL,
5   PRIMARY KEY (`employee_id`)
6 ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
7  
8 CREATE TABLE `project` (
9   `project_id` int(11) NOT NULL AUTO_INCREMENT,
10   `title` varchar(50) DEFAULT NULL,
11   PRIMARY KEY (`project_id`)
12 ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
13  
14 CREATE TABLE `employee_project` (
15   `employee_id` int(11) NOT NULL,
16   `project_id` int(11) NOT NULL,
17   PRIMARY KEY (`employee_id`,`project_id`),
18   KEY `project_id` (`project_id`),
19   CONSTRAINT `employee_project_ibfk_1`
20    FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`),
21   CONSTRAINT `employee_project_ibfk_2`
22    FOREIGN KEY (`project_id`) REFERENCES `project` (`project_id`)
23 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

With the database set up, next step would be the preparation of the Maven
dependencies and Hibernate con guration. For information on this, please
refer to the article on Guide to Hibernate4 with Spring (/hibernate-4-spring)

4. The Model Classes

The model classes Employee and Project need to be created with JPA
annotations:

https://www.baeldung.com/hibernate-many-to-many 3/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

1 @Entity
2 @Table(name = "Employee")
3 public class Employee {
4     // ...
5   
6     @ManyToMany(cascade = { CascadeType.ALL })
7     @JoinTable(
8         name = "Employee_Project",
9         joinColumns = { @JoinColumn(name = "employee_id") },
10         inverseJoinColumns = { @JoinColumn(name = "project_id") }
11     )
12     Set<Project> projects = new HashSet<>();
13     
14     // standard constructor/getters/setters
15 }

1 @Entity
2 @Table(name = "Project")
3 public class Project {   
4     // ... 
5   
6     @ManyToMany(mappedBy = "projects")
7     private Set<Employee> employees = new HashSet<>();
8      
9     // standard constructors/getters/setters  
10 }

As we can see, 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. Let’s have a closer look at them.
The @ManyToMany annotation is used in both classes to create the many-to-
many relationship between the entities.
This association has two sides i.e. the owning side and the inverse side. In
our example, the owning side is Employee so the join table is speci ed on the
owning side by using the @JoinTable annotation in Employee class. The
@JoinTable is used to de ne 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.

https://www.baeldung.com/hibernate-many-to-many 4/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

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.

5. Execution

In order to see the many-to-many annotation in action, we can write the


following JUnit test:

https://www.baeldung.com/hibernate-many-to-many 5/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

1 public class HibernateManyToManyAnnotationMainIntegrationTest {


2     private static SessionFactory sessionFactory;
3     private Session session;
4  
5     // ...
6  
7     @Test
8     public void givenData_whenInsert_thenCreatesMtoMrelationship() {
9         String[] employeeData = { "Peter Oven", "Allan Norman" };
10         String[] projectData = { "IT Project", "Networking Project" };
11         Set<Project> projects = new HashSet<>();
12  
13         for (String proj : projectData) {
14             projects.add(new Project(proj));
15         }
16  
17         for (String emp : employeeData) {
18             Employee employee = new Employee(emp.split(" ")[0],
19               emp.split(" ")[1]);
20   
21             assertEquals(0, employee.getProjects().size());
22             employee.setProjects(projects);
23             session.persist(employee);
24   
25             assertNotNull(employee);
26         }
27     }
28  
29     @Test
30     public void givenSession_whenRead_thenReturnsMtoMdata() {
31         @SuppressWarnings("unchecked")
32         List<Employee> employeeList = session.createQuery("FROM Employe
33           .list();
34   
35         assertNotNull(employeeList);
36   
37         for(Employee employee : employeeList) {
38             assertNotNull(employee.getProjects());
39         }
40     }
41  
42     // ...
43 }

We can see the many-to-many relationship between the two entities created
in the database: the employee, project, and employee_project tables with
sample data representing the relationship.
https://www.baeldung.com/hibernate-many-to-many 6/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

6. Conclusion

In this tutorial, we saw how to create mappings using Hibernate’s many-to-


many annotations, which is a more convenient counterpart compared to
creating XML mapping les.
The source code of this tutorial can be found over on GitHub
(https://github.com/eugenp/tutorials/tree/master/persistence-
modules/spring-hibernate-5).

I just announced the new Learn Spring course,


focused on the fundamentals of Spring 5 and Spring
Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

An intro SPRING data, JPA and


https://www.baeldung.com/hibernate-many-to-many 7/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

Transaction Semantics Details with JPA

Get Persistence right with Spring

Enter your email address

Download

CATEGORIES

SPRING (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SPRING/)
REST (HTTPS://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)
JACKSON (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JSON/JACKSON/)
HTTP CLIENT (HTTPS://WWW.BAELDUNG.COM/CATEGORY/HTTP/)
KOTLIN (HTTPS://WWW.BAELDUNG.COM/CATEGORY/KOTLIN/)

SERIES

JAVA “BACK TO BASICS” TUTORIAL (/JAVA-TUTORIAL)


JACKSON JSON TUTORIAL (/JACKSON)
HTTPCLIENT 4 TUTORIAL (/HTTPCLIENT-GUIDE)
REST WITH SPRING TUTORIAL (/REST-WITH-SPRING-SERIES)
SPRING PERSISTENCE TUTORIAL (/PERSISTENCE-WITH-SPRING-SERIES)
SECURITY WITH SPRING (/SECURITY-SPRING)

https://www.baeldung.com/hibernate-many-to-many 8/9
5/31/2019 Hibernate Many to Many Annotation Tutorial | Baeldung

ABOUT

ABOUT BAELDUNG (/ABOUT)


THE COURSES (HTTPS://COURSES.BAELDUNG.COM)
CONSULTING WORK (/CONSULTING)
META BAELDUNG (HTTP://META.BAELDUNG.COM/)
THE FULL ARCHIVE (/FULL_ARCHIVE)
WRITE FOR BAELDUNG (/CONTRIBUTION-GUIDELINES)
EDITORS (/EDITORS)
OUR PARTNERS (/PARTNERS)
ADVERTISE ON BAELDUNG (/ADVERTISE)

TERMS OF SERVICE (/TERMS-OF-SERVICE)


PRIVACY POLICY (/PRIVACY-POLICY)
COMPANY INFO (/BAELDUNG-COMPANY-INFO)
CONTACT (/CONTACT)

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

S-ar putea să vă placă și