The role column does not appear in the Postgresql table - spring-boot

I'm new to spring boot and jpa and have created this entity called user which has #OneToMany mapping to another table that is role. When I boot the project, every column appears except role. I do not understand what I'm doing wrong here. My role entity looks like this -
Role
package com.userservice.usermanagement.models;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "roles")
public class Role2 {
/**
* Model for role with all the attributes
*/
#Id
#GeneratedValue
#Column(name = "role_id", nullable = false, length = 1024)
private int role_id;
#Column(name = "name", nullable = false, length = 1024)
private String name;
public Role2() {
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And User
package com.userservice.usermanagement.models;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "users")
public class User2 {
/**
* User model
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, length = 1024)
private int id;
#Column(name = "username", nullable = false, length = 1024)
private String username;
#Column(name = "email", nullable = false, length = 1024)
private String email;
#Column(name = "password", nullable = false, length = 1024)
private String password;
#Column(name = "customername", nullable = false, length = 1024)
private String customername;
#Column(name = "customerid", nullable = false, length = 1024)
private String customerid;
#Column(name = "description", nullable = false, length = 1024)
private String description;
#OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
#JoinTable(name="user_role", joinColumns=#JoinColumn(name="id"), inverseJoinColumns=#JoinColumn(name="role_id"))
private Set<Role2> roles = new HashSet<>();;
public User2() {
}
public User2(String username, String email, String customername,String customerid,String description, String password) {
this.username = username;
this.email = email;
this.customername = customername;
this.customerid = customerid;
this.description = description;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int 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 String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getCustomerid() {
return customerid;
}
public void setCustomerid(String customerid) {
this.customerid = customerid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Role2> getRoles() {
return roles;
}
public void setRoles(Set<Role2> roles) {
this.roles = roles;
}
}
In user if I use jointable and post data, everything else shows up but user_role and roles is empty. If I remove jointable to have the column in the User table itself, the role column is missing from user table. Can someone point me in the right direction.

You need to remove
#JoinTable(name="user_role", joinColumns=#JoinColumn(name="id"),
inverseJoinColumns=#JoinColumn(name="role_id"))
because it's for ManyToMany relationship and instead just put:
#JoinColumn(name="user_id")
With this you going to have a user_id field in Role table, and it's going to work.

Related

Targeting unmapped class error in Spring boot app

I work on basic exemplary app that is about #OneToMany & ManyToOne annotation. I define mapping between two classes, apparently there is no error but on running app it gives me an error : Use of #OneToMany or #ManyToMany targeting an unmapped class: com.orchard.orchard.model.AppUser.userRole[ com.orchard.orchard.model.UserRole]
I'm failed to understand where does problem lies as mapping also describe in AppUser. I'd be grateful for the help.
Classes are as follows:
AppUser.java
package com.orchard.orchard.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
#Entity
public class AppUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(updatable = false, nullable = false)
private Integer id;
private String name;
#Column(unique = true)
private String username;
private String password;
private String email;
#Column(columnDefinition = "text")
private String bio;
private Date createdDate;
#OneToMany(mappedBy = "appUser", cascade = CascadeType.ALL, fetch =
FetchType.EAGER)
private Set<UserRole> userRole = new HashSet<>();
public AppUser() {
}
public AppUser(Integer id, String name, String username, String
password, String email, String bio,
Date createdDate, Set<UserRole> userRoles) {
this.id = id;
this.name = name;
this.username = username;
this.password = password;
this.email = email;
this.bio = bio;
this.createdDate = createdDate;
this.userRole = userRoles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Set<UserRole> getUserRoles() {
return userRole;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRole = userRoles;
}
}
UserRole.java
package com.orchard.orchard.model;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long userRoleId;
#ManyToOne
#JoinColumn(name = "user_id")
#JsonIgnore
private AppUser appUser;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "role_id")
private Role role;
public UserRole() {
}
public UserRole(long userRoleId, AppUser appUser, Role role) {
this.userRoleId = userRoleId;
this.appUser = appUser;
this.role = role;
}
public long getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(long userRoleId) {
this.userRoleId = userRoleId;
}
public AppUser getAppUser() {
return appUser;
}
public void setAppUser(AppUser appUser) {
this.appUser = appUser;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
You forgot to add #Entity annotation to your UserRole class
#Entity
public class UserRole {
}

How to query a many to many relation with a condition in Spring Boot JPA

I guess this is a really simple question, but I am not able to find out any solution! Neither google it.
I am working with Spring Boot JPA repositories, and I have a many to many relation between two tables. Table A --> User, table B --> Role.
The data is already recorded in the database, but how can I get for example all the roles that a specific user has?
I have successfully executed the simple queries. Get all users, get all roles, get user by id, etc. But I cannot get this one.
Any suggestion?
Thank you so much!!
package com.mb.model;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String email;
private String firstName;
private String lastName;
private String password;
private boolean enabled;
private boolean tokenExpired;
#ManyToMany
#JoinTable(name = "user_roles", joinColumns = #JoinColumn(name = "user_userId"), inverseJoinColumns = #JoinColumn(name = "role_roleId"))
private Set<Role> roles;
public User() {
super();
}
public User(String email, String firstName, String lastName, String password) {
super();
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
}
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 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 boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isTokenExpired() {
return tokenExpired;
}
public void setTokenExpired(boolean tokenExpired) {
this.tokenExpired = tokenExpired;
}
public Integer getUserId() {
return userId;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
package com.mb.model;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Role {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int roleId;
private String name;
#ManyToMany(mappedBy = "roles")
private Set<User> users;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public int getRoleId() {
return roleId;
}
}
package com.mb.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mb.model.Role;
import com.mb.model.User;
public interface IUserRepo extends JpaRepository<User, Integer>{
User findByEmail(String email);
}
package com.mb.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mb.model.Role;
public interface IRoleRepo extends JpaRepository<Role, Integer>{
}
#Autowired
private IUserRepo repo;
User loggedUser = repo.findByEmail(username);

Function saves new record for room table instead of booking table (booking table has room_id as foreign key)

Ive tried to save record for booking in the bookings table, but it does not create a record and instead adds a room for the room table which i do not want as the room table is not supposed to change, only records of bookings should be added into the bookings table with a foreign key room_id of the room that was booked.
Any help would be much appreciated! Thanks!
Tbl_Bookings Entity
package com.sam.ResourceBookingMS.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
#Entity
#Table(name = "Tbl_Bookings")
public class Tbl_Bookings implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "booking_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Integer getEmployee_id() {
return employee_id;
}
public void setEmployee_id(Integer employee_id) {
this.employee_id = employee_id;
}
public Integer getEquipment_id() {
return equipment_id;
}
public void setEquipment_id(Integer equipment_id) {
this.equipment_id = equipment_id;
}
#Column(name = "type")
private String type;
#Column(name = "date")
private String date;
#Column(name = "time")
private String time;
#Column(name = "employee_id")
private Integer employee_id;
#Column(name = "equipment_id")
private Integer equipment_id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "room_id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Tbl_Rooms thisroom;
public Tbl_Rooms getThisroom() {
return thisroom;
}
public void setThisroom(Tbl_Rooms thisroom) {
this.thisroom = thisroom;
}
public Tbl_Bookings() {
}
public Tbl_Bookings(String type, String date, String time, Integer employee_id, Integer equipment_id) {
this.type = type;
this.date = date;
this.time = time;
this.employee_id = employee_id;
this.equipment_id = equipment_id;
}
}
Tbl_Rooms Entity
package com.sam.ResourceBookingMS.model;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Tbl_Rooms")
public class Tbl_Rooms implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "room_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCapacity() {
return capacity;
}
public void setCapacity(String capacity) {
this.capacity = capacity;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "capacity")
private String capacity;
#Column(name = "location")
private String location;
#Column(name = "description")
private String description;
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "id", orphanRemoval = false, fetch = FetchType.LAZY)
private Set<Tbl_Bookings> bookings;
public Set<Tbl_Bookings> getBookings() {
return bookings;
}
public void setBookings(Set<Tbl_Bookings> bookings) {
this.bookings = bookings;
}
public Tbl_Rooms() {
}
public Tbl_Rooms(String name, String capacity, String location, String description) {
this.name = name;
this.capacity = capacity;
this.location = location;
this.description = description;
}
}
Controller
package com.sam.ResourceBookingMS;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.sam.ResourceBookingMS.model.Tbl_Bookings;
import com.sam.ResourceBookingMS.model.Tbl_Rooms;
#RestController
public class BookRmController {
#Autowired
private TblBkRepository tbr;
#Autowired
private TblRmRepository trr;
#Autowired
private EntityManager entityManager;
#RequestMapping(value = "/bookRm", method = RequestMethod.POST)
#ResponseBody
public String sendData(#RequestBody Tbl_Bookings bk) {
Tbl_Rooms rm = entityManager.getReference(Tbl_Rooms.class, 1);
System.out.println(rm.getId());
Tbl_Bookings booking = new Tbl_Bookings();
booking.setDate(bk.getDate());
booking.setType(bk.getType());
booking.setTime(bk.getTime());
Tbl_Rooms room = new Tbl_Rooms();
room.setCapacity(rm.getCapacity());
room.setDescription(rm.getDescription());
room.setLocation(rm.getLocation());
room.setName(rm.getName());
Set<Tbl_Bookings> bookingOfRoom = new HashSet<Tbl_Bookings>();
bookingOfRoom.add(booking);
room.setBookings(bookingOfRoom);
booking.setThisroom(room);
trr.save(room);
return "Confirmed";
}
}
This is the json data being sent to the controller.
{"room_id":2,"date":"2019-07-26","time":"10:00am to 10:30am","type":"Room"}
mappedBy in parent must be matched with a name defined in the child
(change id to thisroom)
case: "save Child with Parents ID" (might be above UseCase)
For that, we have to request the Child Entity with Parent ID (see JSON request at the controller and set the Parent for that Child) and using Child Repository save the object instead of using parent repository.
case: "save child-parent at same request"
For that, we have to request the Parent Entity which has multiple children (for OneToMany) and using for setting the childerns
Parent
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY, cascade=CascadeType.ALL)
private Set<Tbl_Bookings> bookings;
Child
#ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "room_id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Tbl_Rooms thisroom;
Parent-Child Relationship for referance
Parent.java
#Entity
#Table(name = "parent")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int parentId;
private String name;
#OneToMany(mappedBy="parent",fetch=FetchType.LAZY,cascade = CascadeType.PERSIST)
private List<Child> child = new ArrayList<Child>();
}
Child.java
#Entity
#Table(name = "child")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int childId;
private String account;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class)
#JoinColumn(name="parentId", referencedColumnName = "parentId", nullable = false)
private Parent parent;
}
Controller
#RestController
public class RelationshipController {
#Autowired ParentRepository parentRepository;
#Autowired ChildRepository childRepository;
//save Child with Parent at same
#PostMapping(value = "/onetomany")
public String OneToMany(#RequestBody Parent parent)
{
for (Child child : parent.getChild()) {
child.setParent(parent);
}
parent.setChild(parent.getChild());
parentRepository.save(parent);
return "saved";
/*{
"name":"Romil",
"child":[
{"account":"1"},
{"account":"2"}
]
}*/
}
//save Child with Parent's ID
#PostMapping(value = "/onetomanyPID")
public String OneToMany(#RequestBody Child child)
{
child.setParent(child.getParent());;
childRepository.save(child);
return "saved";
/*{
"account":"3",
"parent":{
"parentId":"1",
"name":"Romil"
}
}*/
}
}
UPDATE
Controller
#PostMapping("/save")
public String save(#RequestBody Tbl_Bookings bookings)
{
bookings.setThisroom(bookings.getThisroom());
tbr.save(bookings);
return "Confirmed";
}
JSON
{
"thisroom":{
"id":"1"
},
"date":"2019-07-26",
"time":"10:00am to 10:30am",
"type":"Room"
}
Tbl_Bookings
#Entity
#Table(name = "Tbl_Bookings")
public class Tbl_Bookings implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "booking_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", referencedColumnName = "room_id")
private Tbl_Rooms thisroom;
}
Tbl_Rooms
#Entity
#Table(name = "Tbl_Rooms")
public class Tbl_Rooms implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "room_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY, cascade=CascadeType.ALL)
private List<Tbl_Bookings> bookings = new ArrayList<Tbl_Bookings>();
}
There are two points you made mistakes.
First) You need to change OneToMany relation in Tbl_Rooms class as below:
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY)
private Set<Tbl_Bookings> bookings;
The mappedBy attribute should be the class member of owner side.
Second) You create a new Tbl_Rooms instance in controller. So it is natural a new record would be created for rooms too.

Spring (Hibernate) - incomplete serialization result / many-to-many

Rest Application / Spring MVC - 3 entities: User, AccessRole, AccessPermision.
Each user has only one role, each role has one or more privileges.
The problem occurs during serialization of users with the same role.
In such case, the JSON serialization result, contains permissions only for the first user.
User Entity
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import socialcreek.access.model.AccessRole;
import socialcreek.user.views.UserViews;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "users")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class User {
/**-----------------------------------------------------
* Constructor
-------------------------------------------------------*/
public User(){ }
public User(String username, String password, AccessRole accessRole) {
this.username = username;
this.password = password;
this.userAccessRole = accessRole;
}
/**-----------------------------------------------------
* Entity Properties
-------------------------------------------------------*/
#Column()
#Id
#JsonView(UserViews.BasicView.class)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonView(UserViews.BasicView.class)
private String username;
private String password;
#JsonView(UserViews.BasicView.class)
#ManyToMany(mappedBy = "users",fetch=FetchType.EAGER)
private Set<UsersGroup> usersGroups;
#ManyToOne(targetEntity = AccessRole.class, optional = false,fetch = FetchType.EAGER, cascade=CascadeType.MERGE)
#JoinColumn(name = "user_role")
#JsonView(UserViews.BasicView.class)
private AccessRole userAccessRole;
/**-----------------------------------------------------
* Setters & Getters
-------------------------------------------------------*/
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<UsersGroup> getUsersGroups() {
return usersGroups;
}
public void setUsersGroups(Set<UsersGroup> usersGroups) {
this.usersGroups = usersGroups;
}
public AccessRole getUserAccessRole() {
return userAccessRole;
}
public void setUserAccessRole(AccessRole userAccessRole) {
this.userAccessRole = userAccessRole;
}
}
AccessRole Entity
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import socialcreek.user.views.UserViews;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "access_role")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class AccessRole {
/**-----------------------------------------------------
* Entity Properties
-------------------------------------------------------*/
#Id
#JsonView(UserViews.BasicView.class)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonView(UserViews.BasicView.class)
private String roleName;
#JsonView(UserViews.BasicView.class)
#ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinTable(name = "access_role_permissions")
private Set<AccessPermission> accessPermissions;
/**-----------------------------------------------------
* Setters & Getters
-------------------------------------------------------*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Set<AccessPermission> getAccessPermissions() {
return accessPermissions;
}
public void setAccessPermissions(Set<AccessPermission> accessPermissions) {
this.accessPermissions = accessPermissions;
}
}
AccessPermission Entity
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import socialcreek.user.views.UserViews;
import javax.persistence.*;
#Entity
#Table(name = "access_permission")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class AccessPermission {
/**-----------------------------------------------------
* Entity Properties
-------------------------------------------------------*/
#Id
#JsonView(UserViews.BasicView.class)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonView(UserViews.BasicView.class)
private String permissionName;
/**-----------------------------------------------------
* Setters & Getters
-------------------------------------------------------*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
}
Serialization Result:
[ { "id":70, "username":"admin", "usersGroups":[], "userAccessRole":{
"id":68, "roleName":"ROLE_ADMIN", "accessPermissions":[
{
"id":69,
"permissionName":"FULL_ACCESS"
}]} },
{ "id":71, "username":"admin2", "usersGroups":[], "userAccessRole":68}
]
Please, have a look at accessRole and accessPermision information - it's complete only for the user:admin. In case of user:admin2 there is only information about accessRoleId ( no information about roleName, accessPermision)
It happens only when both users have the same accessRole. If I change accessRole of user:admin2 to another role - everythnink will be ok.
I found the similar issue with the correct answer (https://stackoverflow.com/a/27117097/4694022).
The problem is caused by #JsonIdentityInfo. After I removed it - it works ...now I need to find the solution to handle serialization for recursive structure but it's another story ...

Hibernate Query to join two table using Jparepository

Hi all i have a small issue with joining two tables using jparepository using #query but i am getting error. please help me with this.
UserAddress.java
package com.surya_spring.example.Model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "user_address")
//#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class UserAddress implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3570928575182329616L;
/*#ManyToMany(cascade = {CascadeType.ALL},fetch=FetchType.EAGER,mappedBy = "userAddress",targetEntity=UserData.class)*/
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="user_id")
private UserData userdata;
#Id
#Column(name = "addr_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long addrid;
#Column(name = "dr_no")
#NotNull
private String doorNo;
#Column(name = "strt_name")
#NotNull
private String streetName;
#Column(name = "city")
#NotNull
private String city;
#Column(name = "country")
#NotNull
private String country;
/*#OneToOne(cascade=CascadeType.ALL)
#Column(name="user_id")*/
public UserData getUserdata() {
return userdata;
}
public void setUserdata(UserData userdata) {
this.userdata = userdata;
}
public Long getAddrid() {
return addrid;
}
public void setAddrid(Long addrid) {
this.addrid = addrid;
}
public String getDoorNo() {
return doorNo;
}
public void setDoorNo(String doorNo) {
this.doorNo = doorNo;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
UserData.java
package com.surya_spring.example.Model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.NonNull;
#Entity
#Table(name = "user_data")
public class UserData implements Serializable{
/**
* Serialization ID
*/
private static final long serialVersionUID = 8133309714576433031L;
/*#ManyToMany(targetEntity=UserAddress.class ,cascade= {CascadeType.ALL },fetch=FetchType.EAGER)
#JoinTable(name="userdata",joinColumns= #JoinColumn(name="userid"),inverseJoinColumns = #JoinColumn(name="userid"))
*/
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
#Column(name = "user_name")
#NonNull
private String userName;
#Column(name = "user_email")
#NonNull
private String userEmail;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
}
Repository:
package com.surya_spring.example.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.surya_spring.example.Model.UserData;
public interface UserDataRepository extends JpaRepository<UserData, Long>{
#Query(" FROM UserData where userId= :id")
public List<UserData> findBySearchTerm(#Param("id") Long id);
}
any one let me know the query to join this both the table to get city name from user_address where user_id=? joining user_data table
If you want to get the city for a user you can do:
#Query("SELECT ua.city FROM UserAddress ua WHERE ua.userdata.userId = ?1")
String findCityByUserId(Long userId);
Note that your entity names are used (like in your java classes) and not the table names in database! You do not have to do the join by yourself as you can use the properties of your domain models to access the related data

Resources