{{announcement.body}}
{{announcement.title}}

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

Java


Role Entity

Java


User Controller

Java


Role Controller

Java


Role Repository

Java


User Repository

Java


Role Service

Java


User Service

Java


We will modify the update method in the next article.

application.properties

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


Topics:
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 }}