Introduction to Spring Data JPA Part 7: Unidirectional Many-to-Many Relationships

DZone 's Guide to

Introduction to Spring Data JPA Part 7: Unidirectional Many-to-Many Relationships

In this article, we discuss how to create many-to-many, unidirectional relationships with Spring Data JPA.

· Java Zone ·
Free Resource

We will discuss the following:

  • Unidirectional many-to-many relations.
  • CRUD Operations.

Let us start by modeling the entities.
Loading entitiesLet us see how Hibernate creates the tables for us.
Hibernate creating tablesA mapping table is created.

Since it is a Many-to-Many, Unidirectional relationship, the definition in the User is as follows, and the role entity will not have any definition.

The only thing that has to be noted is the definition of the relation in the User Entity.

@ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL)

private List<Role> roles; 

Let us see how it translates to code. All CRUD operations are done in the following code. We will modify the UPDATE methods in the next article. The code has been explained in the previous articles. I have attached a video tutorial too for a detailed explanation of the code.

User Entity


Role Entity


User Controller


Role Controller


Role Repository


User Repository


Role Service


User Service


We will modify the update method in the next article.


Properties files

Please find the source code at https://github.com/gudpick/jpa-demo/tree/many-to-many-unidirecctional-starter

Please find the video tutorials

jpa ,microservices ,oauth 2 ,spring boot ,spring data jpa ,spring security

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}