Introduction to Spring Data JPA Part 7: Unidirectional Many-to-Many Relationships
Join the DZone community and get the full member experience.
Join For FreeWe will discuss the following:
- Unidirectional many-to-many relations.
- CRUD Operations.
Let us start by modeling the entities.
Let us see how Hibernate creates the tables for us.
A 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
xxxxxxxxxx
package com.notyfyd.entity;
import javax.persistence.*;
import java.util.List;
name = "t_user") (
public class User {
strategy = GenerationType.IDENTITY) (
private Long id;
private String firstName;
private String lastName;
private String mobile;
unique = true) (
private String email;
targetEntity = Role.class,cascade = CascadeType.ALL) (
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Role Entity
xxxxxxxxxx
package com.notyfyd.entity;
import javax.persistence.*;
name = "t_role") (
public class Role {
strategy = GenerationType.IDENTITY) (
private Long id;
private String name;
private String description;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
User Controller
xxxxxxxxxx
package com.notyfyd.controller;
import com.notyfyd.entity.User;
import com.notyfyd.repository.UserRepository;
import com.notyfyd.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
public class UserController {
private UserService userService;
private UserRepository userRepository;
public UserController(UserService userService, UserRepository userRepository) {
this.userService = userService;
this.userRepository = userRepository;
}
//
"/user/create") (
public ResponseEntity<Object> createUser( User user) {
return userService.createUser(user);
}
"/user/details/{id}") (
public User getUser( Long id) {
if(userRepository.findById(id).isPresent())
return userRepository.findById(id).get();
else return null;
}
"/user/all") (
public List<User> getUsers() {
return userRepository.findAll();
}
"/user/update/{id}") (
public ResponseEntity<Object> updateUser( Long id, User user) {
return userService.updateUser(user, id);
}
"user/delete/{id}") (
public ResponseEntity<Object> deleteUser( Long id) {
return userService.deleteUser(id);
}
}
Role Controller
xxxxxxxxxx
package com.notyfyd.controller;
import com.notyfyd.entity.Role;
import com.notyfyd.repository.RoleRepository;
import com.notyfyd.service.RoleService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
public class RoleController {
private RoleService roleService;
private RoleRepository roleRepository;
public RoleController(RoleService roleService, RoleRepository roleRepository) {
this.roleService = roleService;
this.roleRepository = roleRepository;
}
"/role/create") (
public ResponseEntity<Object> createRole( Role role) {
return roleService.addRole(role);
}
"/role/delete/{id}") (
public ResponseEntity<Object> deleteRole( Long id) {
return roleService.deleteRole(id);
}
"/role/details/{id}") (
public Role getRole( Long id) {
if(roleRepository.findById(id).isPresent())
return roleRepository.findById(id).get();
else return null;
}
"/role/all") (
public List<Role> getRoles() {
return roleRepository.findAll();
}
"/role/update/{id}") (
public ResponseEntity<Object> updateRole( Long id, Role role) {
return roleService.updateRole(id, role);
}
}
Role Repository
xxxxxxxxxx
package com.notyfyd.repository;
import com.notyfyd.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(String name);
}
User Repository
xxxxxxxxxx
package com.notyfyd.repository;
import com.notyfyd.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}
Role Service
xxxxxxxxxx
package com.notyfyd.service;
import com.notyfyd.entity.Role;
import com.notyfyd.repository.RoleRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
public class RoleService {
private RoleRepository roleRepository;
public RoleService(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
/** Create a new role */
public ResponseEntity<Object> addRole(Role role) {
Role newRole = new Role();
newRole.setName(role.getName());
newRole.setDescription(role.getDescription());
Role savedRole = roleRepository.save(newRole);
if(roleRepository.findById(savedRole.getId()).isPresent()) {
return ResponseEntity.accepted().body("Successfully Created Role ");
} else
return ResponseEntity.unprocessableEntity().body("Failed to Create specified Role");
}
/** Delete a specified role given the id */
public ResponseEntity<Object> deleteRole(Long id) {
if(roleRepository.findById(id).isPresent()){
roleRepository.deleteById(id);
if(roleRepository.findById(id).isPresent()){
return ResponseEntity.unprocessableEntity().body("Failed to delete the specified record");
} else return ResponseEntity.ok().body("Successfully deleted specified record");
} else
return ResponseEntity.unprocessableEntity().body("No Records Found");
}
/** Update a Role */
public ResponseEntity<Object> updateRole(Long id, Role role) {
if(roleRepository.findById(id).isPresent()){
Role newRole = roleRepository.findById(id).get();
newRole.setName(role.getName());
newRole.setDescription(role.getDescription());
Role savedRole = roleRepository.save(newRole);
if(roleRepository.findById(id).isPresent())
return ResponseEntity.accepted().body("Role saved successfully");
else return ResponseEntity.badRequest().body("Failed to update Role");
} else return ResponseEntity.unprocessableEntity().body("Specified Role not found");
}
}
User Service
xxxxxxxxxx
package com.notyfyd.service;
import com.notyfyd.entity.User;
import com.notyfyd.repository.RoleRepository;
import com.notyfyd.repository.UserRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
public class UserService {
private UserRepository userRepository;
private RoleRepository roleRepository;
public UserService(UserRepository userRepository, RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
/** Create a new User */
public ResponseEntity<Object> createUser(User model) {
User user = new User();
if (userRepository.findByEmail(model.getEmail()).isPresent()) {
return ResponseEntity.badRequest().body("The Email is already Present, Failed to Create new User");
} else {
user.setFirstName(model.getFirstName());
user.setLastName(model.getLastName());
user.setMobile(model.getMobile());
user.setEmail(model.getEmail());
user.setRoles(model.getRoles());
User savedUser = userRepository.save(user);
if (userRepository.findById(savedUser.getId()).isPresent())
return ResponseEntity.ok("User Created Successfully");
else return ResponseEntity.unprocessableEntity().body("Failed Creating User as Specified");
}
}
/** Update an Existing User */
public ResponseEntity<Object> updateUser(User user, Long id) {
if(userRepository.findById(id).isPresent()) {
User newUser = userRepository.findById(id).get();
newUser.setFirstName(user.getFirstName());
newUser.setLastName(user.getLastName());
newUser.setMobile(user.getMobile());
newUser.setEmail(user.getEmail());
newUser.setRoles(user.getRoles());
User savedUser = userRepository.save(newUser);
if(userRepository.findById(savedUser.getId()).isPresent())
return ResponseEntity.accepted().body("User updated successfully");
else return ResponseEntity.unprocessableEntity().body("Failed updating the user specified");
} else return ResponseEntity.unprocessableEntity().body("Cannot find the user specified");
}
/** Delete an User*/
public ResponseEntity<Object> deleteUser(Long id) {
if (userRepository.findById(id).isPresent()) {
userRepository.deleteById(id);
if (userRepository.findById(id).isPresent())
return ResponseEntity.unprocessableEntity().body("Failed to Delete the specified User");
else return ResponseEntity.ok().body("Successfully deleted the specified user");
} else return ResponseEntity.badRequest().body("Cannot find the user specified");
}
}
We will modify the update method in the next article.
application.properties
xxxxxxxxxx
server.port=2003
spring.datasource.driver-class-name= org.postgresql.Driver
spring.datasource.url= jdbc:postgresql://192.168.64.6:30432/jpa-test
spring.datasource.username = postgres
spring.datasource.password = root
spring.jpa.show-sql=true
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
Opinions expressed by DZone contributors are their own.
Comments