DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Introduction to Spring Data JPA Part 8: Many-to-Many Bidirectional
  • Introduction to Spring Data JPA - Part 6 Bidirectional One to One Relations
  • Introduction to Spring Data JPA — Part 4 Bidirectional One-to-Many Relations
  • Introduction to Spring Data JPA, Part 3: Unidirectional One to Many Relations

Trending

  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Solid Testing Strategies for Salesforce Releases
  • Contextual AI Integration for Agile Product Teams
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  1. DZone
  2. Data Engineering
  3. Databases
  4. Introduction to Spring Data JPA Part 7: Unidirectional Many-to-Many Relationships

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

By 
Vinu Sagar user avatar
Vinu Sagar
·
May. 17, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
10.1K Views

Join the DZone community and get the full member experience.

Join For Free

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
xxxxxxxxxx
1
62
 
1
package com.notyfyd.entity;
2

          
3
import javax.persistence.*;
4
import java.util.List;
5

          
6
@Entity
7
@Table(name = "t_user")
8
public class User  {
9
    @Id
10
    @GeneratedValue(strategy = GenerationType.IDENTITY)
11
    private Long id;
12
    private String firstName;
13
    private String lastName;
14
    private String mobile;
15
    @Column(unique = true)
16
    private String email;
17
    @ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL)
18
    private List<Role> roles;
19

          
20

          
21
    public List<Role> getRoles() {
22
        return roles;
23
    }
24

          
25
    public void setRoles(List<Role> roles) {
26
        this.roles = roles;
27
    }
28

          
29
    public Long getId() {
30
        return id;
31
    }
32
    public void setId(Long id) {
33
        this.id = id;
34
    }
35
    public String getFirstName() {
36
        return firstName;
37
    }
38
    public void setFirstName(String firstName) {
39
        this.firstName = firstName;
40
    }
41
    public String getLastName() {
42
        return lastName;
43
    }
44
    public void setLastName(String lastName) {
45
        this.lastName = lastName;
46
    }
47
    public String getMobile() {
48
        return mobile;
49
    }
50
    public void setMobile(String mobile) {
51
        this.mobile = mobile;
52
    }
53
    public String getEmail() {
54
        return email;
55
    }
56
    public void setEmail(String email) {
57
        this.email = email;
58
    }
59
}


Role Entity

Java
xxxxxxxxxx
1
37
 
1
package com.notyfyd.entity;
2

          
3
import javax.persistence.*;
4

          
5

          
6

          
7
@Entity
8
@Table(name = "t_role")
9
public class Role    {
10
    @Id
11
    @GeneratedValue(strategy = GenerationType.IDENTITY)
12
    private Long id;
13
    private String name;
14
    private String description;
15

          
16
    public Long getId() {
17
        return this.id;
18
    }
19
    public void setId(Long id) {
20
        this.id = id;
21
    }
22
    public String getName() {
23
        return this.name;
24
    }
25
    public void setName(String name) {
26
        this.name = name;
27
    }
28
    public String getDescription() {
29
        return this.description;
30
    }
31
    public void setDescription(String description) {
32
        this.description = description;
33
    }
34
}


User Controller

Java
xxxxxxxxxx
1
45
 
1
package com.notyfyd.controller;
2

          
3
import com.notyfyd.entity.User;
4
import com.notyfyd.repository.UserRepository;
5
import com.notyfyd.service.UserService;
6
import org.springframework.http.ResponseEntity;
7
import org.springframework.web.bind.annotation.*;
8

          
9
import java.util.List;
10

          
11
@RestController
12
public class UserController {
13

          
14
    private UserService userService;
15
    private UserRepository userRepository;
16

          
17
    public UserController(UserService userService, UserRepository userRepository) {
18
        this.userService = userService;
19
        this.userRepository = userRepository;
20
    }
21
    //
22
    @PostMapping("/user/create")
23
    public ResponseEntity<Object> createUser(@RequestBody User user) {
24
        return userService.createUser(user);
25
    }
26
    @GetMapping("/user/details/{id}")
27
    public User getUser(@PathVariable Long id) {
28
        if(userRepository.findById(id).isPresent())
29
            return userRepository.findById(id).get();
30
        else return  null;
31
    }
32
    @GetMapping("/user/all")
33
    public List<User> getUsers() {
34
        return userRepository.findAll();
35
    }
36
    @PutMapping("/user/update/{id}")
37
    public ResponseEntity<Object> updateUser(@PathVariable Long id, @RequestBody User user) {
38
        return userService.updateUser(user, id);
39
    }
40
    @DeleteMapping("user/delete/{id}")
41
    public ResponseEntity<Object> deleteUser(@PathVariable Long id) {
42
        return userService.deleteUser(id);
43
    }
44
}


Role Controller

Java
xxxxxxxxxx
1
50
 
1
package com.notyfyd.controller;
2

          
3
import com.notyfyd.entity.Role;
4
import com.notyfyd.repository.RoleRepository;
5
import com.notyfyd.service.RoleService;
6
import org.springframework.http.ResponseEntity;
7
import org.springframework.web.bind.annotation.*;
8

          
9
import java.util.List;
10

          
11

          
12
@RestController
13
public class RoleController {
14

          
15
    private RoleService roleService;
16
    private RoleRepository roleRepository;
17

          
18
    public RoleController(RoleService roleService, RoleRepository roleRepository) {
19
        this.roleService = roleService;
20
        this.roleRepository = roleRepository;
21
    }
22

          
23
    @PostMapping("/role/create")
24
    public ResponseEntity<Object> createRole(@RequestBody Role role) {
25
        return  roleService.addRole(role);
26
    }
27
    @DeleteMapping("/role/delete/{id}")
28
    public ResponseEntity<Object> deleteRole(@PathVariable Long id) {
29
        return roleService.deleteRole(id);
30
    }
31
    @GetMapping("/role/details/{id}")
32
    public Role getRole(@PathVariable Long id) {
33
        if(roleRepository.findById(id).isPresent())
34
            return roleRepository.findById(id).get();
35
        else return null;
36
    }
37
    @GetMapping("/role/all")
38
    public List<Role> getRoles() {
39
        return roleRepository.findAll();
40
    }
41
    @PutMapping("/role/update/{id}")
42
    public ResponseEntity<Object> updateRole(@PathVariable Long id, @RequestBody Role role) {
43
        return roleService.updateRole(id, role);
44
    }
45
}


Role Repository

Java
xxxxxxxxxx
1
12
 
1
package com.notyfyd.repository;
2

          
3
import com.notyfyd.entity.Role;
4
import org.springframework.data.jpa.repository.JpaRepository;
5
import org.springframework.stereotype.Repository;
6

          
7
import java.util.Optional;
8

          
9
@Repository
10
public interface RoleRepository extends JpaRepository<Role, Long> {
11
    Optional<Role> findByName(String name);
12
}


User Repository

Java
xxxxxxxxxx
1
12
 
1
package com.notyfyd.repository;
2

          
3
import com.notyfyd.entity.User;
4
import org.springframework.data.jpa.repository.JpaRepository;
5
import org.springframework.stereotype.Repository;
6

          
7
import java.util.Optional;
8

          
9
@Repository
10
public interface UserRepository extends JpaRepository<User, Long> {
11
    Optional<User> findByEmail(String email);
12
}


Role Service

Java
xxxxxxxxxx
1
57
 
1
package com.notyfyd.service;
2

          
3
import com.notyfyd.entity.Role;
4
import com.notyfyd.repository.RoleRepository;
5
import org.springframework.http.ResponseEntity;
6
import org.springframework.stereotype.Service;
7

          
8
@Service
9
public class RoleService {
10

          
11
    private RoleRepository roleRepository;
12

          
13
    public RoleService(RoleRepository roleRepository) {
14
        this.roleRepository = roleRepository;
15
    }
16

          
17

          
18
    /** Create a new role  */
19
    public ResponseEntity<Object> addRole(Role role)  {
20

          
21
        Role newRole = new Role();
22
        newRole.setName(role.getName());
23
        newRole.setDescription(role.getDescription());
24
        Role savedRole = roleRepository.save(newRole);
25
        if(roleRepository.findById(savedRole.getId()).isPresent()) {
26
            return ResponseEntity.accepted().body("Successfully Created Role ");
27
        } else
28
            return ResponseEntity.unprocessableEntity().body("Failed to Create specified Role");
29
    }
30

          
31

          
32
    /** Delete a specified role given the id */
33
    public ResponseEntity<Object> deleteRole(Long id) {
34
        if(roleRepository.findById(id).isPresent()){
35
            roleRepository.deleteById(id);
36
            if(roleRepository.findById(id).isPresent()){
37
                return ResponseEntity.unprocessableEntity().body("Failed to delete the specified record");
38
            } else return ResponseEntity.ok().body("Successfully deleted specified record");
39
        } else
40
            return ResponseEntity.unprocessableEntity().body("No Records Found");
41
    }
42

          
43

          
44
    /** Update a Role */
45
    public ResponseEntity<Object> updateRole(Long id, Role role) {
46
        if(roleRepository.findById(id).isPresent()){
47
            Role newRole = roleRepository.findById(id).get();
48
            newRole.setName(role.getName());
49
            newRole.setDescription(role.getDescription());
50
            Role savedRole = roleRepository.save(newRole);
51
            if(roleRepository.findById(id).isPresent())
52
                return ResponseEntity.accepted().body("Role saved successfully");
53
            else return ResponseEntity.badRequest().body("Failed to update Role");
54

          
55
        } else return ResponseEntity.unprocessableEntity().body("Specified Role not found");
56
    }
57
}


User Service

Java
xxxxxxxxxx
1
64
 
1
package com.notyfyd.service;
2

          
3
import com.notyfyd.entity.User;
4
import com.notyfyd.repository.RoleRepository;
5
import com.notyfyd.repository.UserRepository;
6
import org.springframework.http.ResponseEntity;
7
import org.springframework.stereotype.Service;
8
import org.springframework.transaction.annotation.Transactional;
9

          
10
@Service
11
public class UserService {
12

          
13
    private UserRepository userRepository;
14
    private RoleRepository roleRepository;
15

          
16
    public UserService(UserRepository userRepository, RoleRepository roleRepository) {
17
        this.userRepository = userRepository;
18
        this.roleRepository = roleRepository;
19
    }
20
    /** Create a new User */
21
    public ResponseEntity<Object> createUser(User model) {
22
        User user = new User();
23
        if (userRepository.findByEmail(model.getEmail()).isPresent()) {
24
            return ResponseEntity.badRequest().body("The Email is already Present, Failed to Create new User");
25
        } else {
26
            user.setFirstName(model.getFirstName());
27
            user.setLastName(model.getLastName());
28
            user.setMobile(model.getMobile());
29
            user.setEmail(model.getEmail());
30
            user.setRoles(model.getRoles());
31

          
32
            User savedUser = userRepository.save(user);
33
            if (userRepository.findById(savedUser.getId()).isPresent())
34
                return ResponseEntity.ok("User Created Successfully");
35
            else return ResponseEntity.unprocessableEntity().body("Failed Creating User as Specified");
36
        }
37
    }
38

          
39
    /** Update an Existing User */
40
    @Transactional
41
    public ResponseEntity<Object> updateUser(User user, Long id) {
42
        if(userRepository.findById(id).isPresent()) {
43
            User newUser = userRepository.findById(id).get();
44
            newUser.setFirstName(user.getFirstName());
45
            newUser.setLastName(user.getLastName());
46
            newUser.setMobile(user.getMobile());
47
            newUser.setEmail(user.getEmail());
48
            newUser.setRoles(user.getRoles());
49
            User savedUser = userRepository.save(newUser);
50
            if(userRepository.findById(savedUser.getId()).isPresent())
51
                return  ResponseEntity.accepted().body("User updated successfully");
52
            else return ResponseEntity.unprocessableEntity().body("Failed updating the user specified");
53
        } else return ResponseEntity.unprocessableEntity().body("Cannot find the user specified");
54
    }
55
    /** Delete an User*/
56
    public ResponseEntity<Object> deleteUser(Long id) {
57
        if (userRepository.findById(id).isPresent()) {
58
            userRepository.deleteById(id);
59
            if (userRepository.findById(id).isPresent())
60
                return ResponseEntity.unprocessableEntity().body("Failed to Delete the specified User");
61
            else return ResponseEntity.ok().body("Successfully deleted the specified user");
62
        } else return ResponseEntity.badRequest().body("Cannot find the user specified");
63
    }
64
}


We will modify the update method in the next article.

application.properties

Properties files
xxxxxxxxxx
1
 
1
server.port=2003
2
spring.datasource.driver-class-name= org.postgresql.Driver
3
spring.datasource.url= jdbc:postgresql://192.168.64.6:30432/jpa-test
4
spring.datasource.username = postgres
5
spring.datasource.password = root
6
spring.jpa.show-sql=true
7
spring.jpa.hibernate.ddl-auto=create


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

Please find the video tutorials


Relational database Spring Data Java (programming language) Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Introduction to Spring Data JPA Part 8: Many-to-Many Bidirectional
  • Introduction to Spring Data JPA - Part 6 Bidirectional One to One Relations
  • Introduction to Spring Data JPA — Part 4 Bidirectional One-to-Many Relations
  • Introduction to Spring Data JPA, Part 3: Unidirectional One to Many Relations

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!