Home United States USA — software Introduction to Spring Data JPA Part 8: Many-to-Many Bidirectional

Introduction to Spring Data JPA Part 8: Many-to-Many Bidirectional

363
0
SHARE

In this article, we discuss how to model many-to-many, bidirectional relationships with Spring Data JPA.
Let’s be friends:
Comment (0)
Join the DZone community and get the full member experience.
In this article, we will discuss the following:
Let us start by modeling the entities:You can see the definition of Role in the User entity and the definition of User in Role entity. Hence, we can call it bidirectional. The requirement is that one User can have many Roles, and one Role can be associated with many Users. Hence, it is a Many-to-Many relationship. Let us see what Hibernate gives us by default. A mapping table with users_id and roles_id. Now, let us look at the entities.
Please find the source code at https://github.com/gudpick/jpa-demo/tree/many-to-many-bidirectional-starter
Let us look at the main changes we have made.
The Role Entity
The User Entity
One major change we can find here is the definition of relations.
Here, Role will be the parent entity, and we are using mappedBy=”role” in the role entity. The @ManytoMany annotation shows that it is a Many to Many relationship, and using @ManytoMany annotations at both sides of the relation (i.e.: in Role Entity and User Entity) shows that it is a bidirectional relation.
Now, we are using a new annotation @JsonIdentityInfo. In the previous aricles, we have StackOverflow errors due to circular references. We have been using @JsonIgnore, @JsonManagedReference, and @JsonBackReference to take care of the error. This new annotation, @JsonIdentityInfo, will handle the circular reference errors for us.
We are having the User Controller as follows.
RoleController
Now, let us run the application. Let us create a user with two roles using the following JSON object.
POST: localhost:2003/user/create
This will give a success message. Now, let us create a Role with two users.
POST: localhost:2003/role/create
It should return a success message. Let us see the @JsonIdentityInfo impact on the GET requests. You can try removing this annotation and get the circular reference errors.
GET: localhost:2003/user/all
You should get the result as follows.

Continue reading...