I have a users table which contains the user details. i also have a authorities table which has the role of a user. The user and authorities table has one to many mapping. When i try to save the details using Jpa the foreign key column is blank no data is inserted in that field. i have a form in which i am specifying the role of the user along with other details.
package com.example.StarsProject.Model;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
#Entity
#Table
#Getter
#Setter
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String role;
#ManyToOne(cascade = CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinColumn(name = "users_id", referencedColumnName = "id")
private Users users;
public Authorities(String role){
this.role = role;
}
}
package com.example.StarsProject.Model;
import com.example.StarsProject.DTO.UserDTO;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table
#Getter
#Setter
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "first_name")
private String firstname;
#Column(name = "last_name")
private String lastname;
#Column(unique = true)
private String email;
private String password;
#OneToMany(fetch = FetchType.EAGER,targetEntity = Authorities.class,mappedBy = "users", cascade = CascadeType.PERSIST)
private Set<Authorities> authorities;
public Users(UserDTO userDTO) {
this.email = userDTO.getEmail();
this.firstname = userDTO.getFirstname();
this.lastname = userDTO.getLastname();
this.password = userDTO.getPassword();
// Authorities authorities = new Authorities();
// authorities.setRole(userDTO.getRole());
// Set<Authorities> set = new HashSet<>();
// set.add(authorities);
this.authorities = new HashSet<Authorities>(Arrays.asList(new Authorities(userDTO.getRole())));
}
}
package com.example.StarsProject.Service;
import com.example.StarsProject.DTO.UserDTO;
import com.example.StarsProject.Model.Users;
import com.example.StarsProject.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserDetailsServiceImpl implements UserDetailsServiceInterface{
#Autowired
UserRepository userRepository;
#Override
public void storeUserDetails(UserDTO userDTO) {
Users users = new Users(userDTO);
userRepository.save(users);
}
}
When i try to save the user details it doesn't insert any value in the foreign key column. Can someone tell me what i am doing wrong.
You need to setusers field in Authorities manually. Hibernate won't fill it for you.
Related
I have this POJO class:
package com.weather.weather.entity;
import jakarta.persistence.*;import lombok.Data;
import lombok.NoArgsConstructor;import org.hibernate.annotations.Proxy;import org.springframework.transaction.annotation.Transactional;
import java.util.List;import java.util.Set;
#Entity#Table(name = "users")#Data#NoArgsConstructor
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "collaborator",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id")
)
private Set<Role> roles;
}
Also Role class:
package com.weather.weather.entity;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Proxy;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "roles")
#Data
#NoArgsConstructor
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// #OneToMany(mappedBy = "role")
// private List<User> users;
#ManyToMany(mappedBy = "roles")
private Set<User> users;
}
But always getRoles() are null.
I have tried changing data to #OneToOne, #ManyToOne, #OneToMany.But its always null.At some point, when i was doing #ManyToOne way, i have got this exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.weather.weather.entity.Role.users: could not initialize proxy - no Session
And i found to ways to fix that. I`ve tried putting fetch property, #Proxy(lazy=false), and many many others. Nothing helped
Your annotation #ManyToMany imported from jakarta.persistence.
You should import from javax.persistence.* and you can remove proxy annotation and Lazy fetchType
I am building a spring boot application that allows an admin to view a list of all users saved in my Database. However, at the moment, all users including the ones with an admin role are being displayed. I was suggested to filter out admins in the backend code but I am not sure how to go about doing this. If anyone could help me, it would very much appreciated. Thank you! (I am using JPA + Hibernate)
UPDATE:
I was suggested a solution that was very useful below. I needed to make a getUsers method which queries data from my Database in a way that filters out admins. At first, I was having issues with the SQL part of the query since I am using hibernate (I think, correct me if I am wrong). I was made aware that you can't use a JPQL query to access raw entity data from tables, since I was using #JoinTable to create my user_roles table that doesn't have an entity class for it, I was confused. Seen in my User class as follows:
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable( name = "user_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
I was receiving a red line in my user repository class at user_role ur in FROM User u,Role r, user_role ur. Futhermore, I was receiving the following error: user_role is not mapped [SELECT u.id,u.username,u.email FROM com.Application.models.User u,com.Application.models.Role r, user_role ur WHERE u.id=ur.id AND r.id=ur.id AND r.name<>'ADMIN']. My Role entity is used to map the role ID and the role name whereas my user_role table contains a column of the user ID and the role ID in one table for mapping the user id to a role id. That is where my last error was.
My Solution:
#Query("SELECT u FROM User u join u.roles r WHERE NOT EXISTS" + "(SELECT r FROM u.roles WHERE r.name = 'ROLE_ADMIN')")
List<User> getUsers();
This succesfuly filtered out users with an admin role in my case. I hope this helps someone one day, I was stuck on this for a minute. Thanks for all the help!
User.java:
package com.Application.models;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table( name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username"),
})
public class User {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "username")
#NotBlank
#Size(max = 20)
private String username;
#Column(name = "email")
#NotBlank
#Size(max = 50)
#Email
private String email;
#NotBlank
#Size(max = 120)
private String password;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable( name = "user_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
#OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "user")
private Set<UserPost> userPosts = new HashSet<>();
public User(String username, String email
,String password) {
this.username = username;
this.email = email;
this.password = password;
}
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
TestController.java:
package com.Application.controller;
import com.Application.models.User;
import com.Application.repository.UserPostsRepository;
import com.Application.repository.UserProfileRepository;
import com.Application.repository.UserRepository;
import com.Application.security.jwt.JwtUtils;
import com.Application.security.services.UserDetailsService;
import com.Application.security.services.UserPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#CrossOrigin(origins = "http://localhost:3000")
#RestController
#RequestMapping("/api/test")
public class TestController {
private static final String AUTH_HEADER = "authorization";
#Autowired
private final UserPostsRepository userPostRepo;
#Autowired
private final UserRepository userRepo;
#Autowired
private final UserProfileRepository userProfRepo;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private UserPostService userPostService;
#Autowired
JwtUtils jwtUtils;
public TestController(UserPostsRepository userPostRepo, UserRepository userRepo, UserProfileRepository userProfRepo) {
this.userPostRepo = userPostRepo;
this.userRepo = userRepo;
this.userProfRepo = userProfRepo;
}
#GetMapping("/all")
public String allAccess() {
return "Public Content.";
}
#GetMapping("/user")
#PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
public String userAccess() {
return "User Content.";
}
#GetMapping("/mod")
#PreAuthorize("hasRole('MODERATOR')")
public String moderatorAccess() {
return "Moderator Board.";
}
#GetMapping("/admin")
#PreAuthorize("hasRole('ADMIN')")
public List<User> adminAccess(Model model) {
List<User> allUsers = userRepo.getUsers();
allUsers.forEach(user -> model.addAttribute("username", user.getUsername()));
return allUsers;
}
}
Role.java:
package com.Application.models;
import javax.persistence.*;
#Entity
#Table(name = "roles")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Enumerated(EnumType.STRING)
#Column(length = 20)
private ERole name;
public Role() {
}
public Role(ERole name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public ERole getName() {
return name;
}
public void setName(ERole name) {
this.name = name;
}
}
ERole.java:
package com.Application.models;
public enum ERole {
ROLE_USER,
ROLE_MODERATOR,
ROLE_ADMIN
}
UserRepository.java:
package com.Application.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.Application.models.User;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
User findUserById(Long id);
Optional<User> findByEmail(String email);
List<User> findAll();
#Query("SELECT u.id,u.username,u.email FROM User u,Role r, user_role ur WHERE u.id=ur.id AND r.id=ur.id AND r.name<>\'ADMIN\'") //Error at users u, roles r, user_roles ur even though the table names are right
List<User> getUsers();
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
RoleRepository.java:
package com.Application.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.Application.models.ERole;
import com.Application.models.Role;
#Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(ERole name);
}
There are better ways to do this but here is a simple way.Just add the below method in your repository interface
#Query("SELECT u.firstname,u.lastname,u.email FROM user u,role r,user_role ur WHERE u.id=ur.user_id AND r.id=ur.role_id AND r.name<>\'ADMIN\'")
List<User> getUsers();
getUsers() retuns a list of users except admin users.
Of course you can change the query depending on what columns are in user table and change user_roles with the name of the appropriate table in your database.
Here are my register controller and user service. Why can I not store my password in my database?
When I'm using Postman it returns values of the hashed password, but when I check my database it only stores the "email" and the password is null. Why? Should I create another table Password to store them?
package demo2.demo.Controller;
import demo2.demo.data.model.User;
import demo2.demo.data.service.UserService;
import demo2.demo.model.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class LoginController {
#Autowired
private UserService userService;
#Autowired
private PasswordEncoder passwordEncoder;
#PostMapping(path = "/register")
public User registerNewUser(#RequestBody UserDTO userDTO) {
User user = new User();
user.setEmail(userDTO.getEmail());
user.setPassword(userDTO.getPassword());
userService.register(user);
return user;
}
}
package demo2.demo.data.service;
import demo2.demo.constant.RoleConstant;
import demo2.demo.data.model.User;
import demo2.demo.data.model.UserRole;
import demo2.demo.data.repository.UserRepository;
import demo2.demo.data.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private UserRoleRepository userRoleRepository;
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// find by email
public User findByEmail(String email) {
return (User) userRepository.findUserByEmail(email);
}
// find by id
public User findByID(int id) { return userRepository.findById(id).orElse(null);}
// register
public void register(User user) {
try {
// hash password
user.setPassword(passwordEncoder().encode(user.getPassword()));
// save user
userRepository.save(user);
// tạo quyền role
UserRole userRole = new UserRole();
userRole.setRoleID(RoleConstant.roleUser);
userRole.setUserID(user.getId());
userRoleRepository.save(userRole);
}catch (Exception e) {
e.getMessage();
}
}
}
this is my user_role class
#Entity(name = "dbo_user_role")
public class UserRole {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_role_id")
#Id
private int id;
#Column(name = "role_id")
private int roleID;
#Column(name = "user_id")
private int userID;
// getter&setter
This is role class
#Entity(name = "dbo_role")
public class Role {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "role_id")
#Id
private int id;
private String name;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.MERGE,
CascadeType.PERSIST
})
#JoinTable(name = "dbo_user_role",
joinColumns = {#JoinColumn(name = "role_id")},
inverseJoinColumns = {#JoinColumn(name = "user_id")})
// getter&setter
And this is role class
#Entity(name = "dbo_user")
public class User {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
#Id
private int id;
private String email;
#Transient
private String password;
#Transient avoids the persistence of the password-field.
From https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/Transient.html
Specifies that the property or field is not persistent.
In order to store the contents of the field, remove the #Transient annotation.
I have a many to many relation between Permission and Role classes.
And there is a role_permission table to keep relation between role and permission
CREATE TABLE public.role_permissions
(
role_id bigint NOT NULL,
permission_id bigint NOT NULL,
CONSTRAINT role_permissions_pkey PRIMARY KEY (role_id, permission_id),
CONSTRAINT fkh0v7u4w7mttcu81o8wegayr8e FOREIGN KEY (permission_id)
REFERENCES public.permission (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fklodb7xh4a2xjv39gc3lsop95n FOREIGN KEY (role_id)
REFERENCES public.role (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.role_permissions
OWNER TO postgres;
When I want to delete Permission it throws following error
org.postgresql.util.PSQLException: ERROR: update or delete on table "permission" violates foreign key constraint "fkh0v7u4w7mttcu81o8wegayr8e" on table "role_permissions"
Detail: Key (id)=(6) is still referenced from table "role_permissions".
Here is my class implementations
package com.nova.stats.client.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.PreRemove;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#EqualsAndHashCode(exclude = {"users", "roles"})
#ToString(exclude = {"users", "roles"})
#Entity
public class Permission implements GrantedAuthority {
#Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 2, max=100, message = "Permission name must be between {min} and {max} characters long")
#Column(unique = true)
private String name;
#NotNull
#Size(min = 10, max=250, message = "Permission description must be between {min} and {max} characters long")
#Column
private String description;
#Getter(onMethod = #__(#Override))
#NotNull
#Size(min = 6, max=100, message = "Permission authority must be between {min} and {max} characters long")
#Column(unique = true)
private String authority;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
private Set<Role> roles;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
private Set<User> users;
public Permission(String name, String description, String authority) {
this.name = name;
this.description = description;
this.authority = authority;
}
}
package com.nova.stats.client.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
#Data
#AllArgsConstructor
#NoArgsConstructor
#EqualsAndHashCode(exclude = {"users", "permissions"})
#ToString(exclude = {"users", "permissions"})
#Getter
#Setter
#Entity
public class Role implements GrantedAuthority {
#Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 2, max=100, message = "Role name must be between {min} and {max} characters long")
#Column(unique = true)
private String name;
#NotNull
#Size(min = 10, max=250, message = "Role description must be between {min} and {max} characters long")
#Column
private String description;
#Getter(onMethod = #__(#Override))
#NotNull
#Size(min = 6, max=100, message = "Role authority must be between {min} and {max} characters long")
#Column(unique = true)
private String authority;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>(0);
#Getter(onMethod = #__(#JsonIgnore))
#Setter(onMethod = #__(#JsonProperty("permissions")))
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "role_permissions", joinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "permission_id", referencedColumnName = "id"))
private Set<Permission> permissions;
public Role(String name, String description, String authority, Set<Permission> permissions) {
this(name, description, authority);
this.permissions = permissions;
}
public Role(String name, String description, String authority) {
this.name = name;
this.description = description;
this.authority = authority;
}
}
Here is what I need; when I want to delete any permission then foreign key must be deleted in role_permission table but related role can't be delete. I mean when delete permission, just delete permission on table permission and relation on table role_permission
What should I do for that ?
The problem is that when try to delete a permission, it is still referenced on user. You need to delete the user first or remove it's permission before removing from permission table.
To delete in cascade you can try this:
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "permissions")
private Set<User> users;
I added "#OnDelete(action = OnDeleteAction.CASCADE)" annotation on User and Permission in Role class
And also added Role and User in Permission class
And now, It works as I want
Here is an Example
package com.asd.asd;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Set;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#EqualsAndHashCode(exclude = {"users", "roles"})
#ToString(exclude = {"users", "roles"})
#Entity
public class Permission implements GrantedAuthority {
#Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 2, max=100, message = "Permission name must be between {min} and {max} characters long")
#Column(unique = true)
private String name;
#NotNull
#Size(min = 10, max=250, message = "Permission description must be between {min} and {max} characters long")
#Column
private String description;
#Getter(onMethod = #__(#Override))
#NotNull
#Size(min = 6, max=100, message = "Permission authority must be between {min} and {max} characters long")
#Column(unique = true)
private String authority;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
#OnDelete(action = OnDeleteAction.CASCADE)
private Set<Role> roles;
#Getter(onMethod = #__(#JsonIgnore))
#ManyToMany(mappedBy = "permissions")
#OnDelete(action = OnDeleteAction.CASCADE)
private Set<User> users;
public Permission(String name, String description, String authority) {
this.name = name;
this.description = description;
this.authority = authority;
}
}
I am trying to join three entities (table) using spring-jpa into one table using Many-To-Many relationship.
Three classes are :
1] User
2] Resource
3] Privilege
And I want to combine these three entities into one User_Resource_Privilege table
User Entity
package com.****.acl.domain;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
#Entity
public class User {
#Id #GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
#Column(name="user_id", nullable=false, length=40)
private String userId;
#Column(name="user_name", nullable=false, length=45)
private String userName;
#Column(name="first_name", nullable=true, length=45)
private String firstName;
#Column(name="last_name", nullable=true, length=45)
private String lastName;
#Column(name="email", nullable=true, length=50)
private String email;
public User(){
}
public User(String userName, String firstName, String lastName, String email) {
this.userName = userName;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
getter and setters .......
}
Resource Entity
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
#Entity
public class Resource {
#Id #GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
#Column(name="resource_id", nullable=false, length=40)
private String resourceId;
#Column(name="resource_name", nullable=false, length=45)
private String name;
#Column(name="resource_type", nullable=false, length=45)
private String type;
public Resource(){
}
public Resource(String name, String type) {
this.name = name;
this.type = type;
}
getter and setter ......
}
Privilege Entity
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
#Entity
public class Privilege {
#Id #GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
#Column(name="privilege_id", nullable=false, length=40)
private String privilegeId;
#Column(name="resource_name", nullable=false, length=45)
private String name;
#Column(name="resource_description", nullable=true, length=45)
private String description;
public Privilege(){
}
getters and setters ....
}
Now I want to create one table by joining all the three entities described above.
The join in ER diagram:
Can someone please help me in joining these three tables using Many-To-Many relationship and let me know how to achieve this using spring-jpa and REST ?
Also it will be great if you please explain how to insert data in this "User_Resource_Privilege" table using REST/curl command ?
What you could do is make an embeddable ID and wrap it with the class. You can afterwards even expand this wrapper class to hold other fields.
java geeks example of embedded id
You would get something like
#Embeddable
public class EmbeddedIdClass implements Serializable {
private String userId;
private String resourceId;
private String privilegeId;
// constructors, getters and setters, equals, etc
}
#Entity
public class Wrapper {
#EmbeddedId
private EmbeddedIdClass id;
// constructors, etc
}
Instead of just using the strings in this example, you should use the complete objects and let hibernate (or something like it) do it's stuff. It should only take the id's into the database and do it's magic itself.
edit:
Just wanting to insert the id's as values, but keeping relationships would look something like this
#Entity
public class Wrapper {
#Id
private String id;
private User user;
private Resource resource;
private Privilege privilege;
// constructors
public Wrapper(final User user, final Resource resource, final Privilege privilege) {
this.user = user;
this.resource = resource;
this.privilege = privilege;
}
}