Many-To-Many Relationship:
Many-To-Many relationship is a common relationship type in databases, representing a relationship between two entities, where multiple instances of one entity can be associated with multiple instances of the other entity. In JPA, this relationship can be modeled using the @ManyToMany annotation, which maps the relationship between two entities in a bidirectional manner.
For example, in a user management system, a User entity might have a many-to-many relationship with a Role entity, as a user can have multiple roles, and a role can be assigned to multiple users. To establish a many-to-many relationship in Hibernate, you need to create a join table that holds the foreign keys of the two associated entities. Here’s an example of how to define a many-to-many relationship between a User and a Role entity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;
@Column(name = "user_name")
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
// getters and setters
}
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private Long id;
@Column(name = "role_name")
private String name;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
private Set<User> users = new HashSet<>();
// getters and setters
}
n this example, the @ManyToMany annotation is used to define the many-to-many relationship between the User and Role entities. The joinColumns and inverseJoinColumns elements specify the names of the foreign key columns in the join table, and the mappedBy element is used to specify the inverse side of the relationship.
Save and Retrieve Data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Creating some sample roles
Role role1 = new Role();
role1.setName("ROLE_ADMIN");
session.save(role1);
Role role2 = new Role();
role2.setName("ROLE_USER");
session.save(role2);
// Creating a new user and associating with the roles
User user = new User();
user.setName("John");
Set<Role> roles = new HashSet<>();
roles.add(role1);
roles.add(role2);
user.setRoles(roles);
// Saving the user entity and the association in the join table
session.save(user);
transaction.commit();
// Fetching the user entity and its associated roles
User fetchedUser = session.get(User.class, user.getId());
Set<Role> fetchedRoles = fetchedUser.getRoles();
System.out.println("User " + fetchedUser.getName() + " has the following roles:");
for (Role role : fetchedRoles) {
System.out.println(role.getName());
}
// Fetching a role entity and its associated users
Role fetchedRole = session.get(Role.class, role1.getId());
Set<User> fetchedUsers = fetchedRole.getUsers();
System.out.println("Role " + fetchedRole.getName() + " has the following users:");
for (User user : fetchedUsers) {
System.out.println(user.getName());
}
session.close();
In this example, we start by creating some sample Role entities and persisting them using the session.save() method. Next, we create a new User entity and associate it with the sample roles. We save the user entity using the session.save() method, which also persists the association in the join table.
After committing the transaction, we fetch the user entity and its associated roles using the session.get() method, and print out the role names. Similarly, we fetch a role entity and its associated users, and print out the user names.
Data Visualization
user
user_id | user_name |
---|---|
1 | John |
role
role_id | name |
---|---|
1 | ROLE_ADMIN |
2 | ROLE_USER |
user_role
user_id | role_id |
---|---|
1 | 1 |
1 | 2 |
Conclusion
A many-to-one relationship represents a relationship between two entities where multiple instances of one entity are associated with a single instance of another entity.