Targeting unmapped class error in Spring boot app - spring

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 {
}

Related

The role column does not appear in the Postgresql table

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.

#RequestBody getting parameters values null

I am developing a rest API, but it provides null with #RequestBody. I went through the answers on this platform but it didn't solve my problem. I am unable to find where the problem is. I want to verify the user by validating userEmail and userPassword but didn't succeed.
#RestController
#RequestMapping("user")
public class UserController {
#Autowired
private IUserService userService;
#GetMapping("validateUser")
public ResponseEntity<Boolean> validateUser(#RequestBody Users user) {
boolean validateStatus = userService.validateUser(user.getUserEmail(), user.getUserPassword());
if (validateStatus)
return new ResponseEntity<Boolean>(validateStatus, HttpStatus.OK);
else
return new ResponseEntity<Boolean>(validateStatus, HttpStatus.UNAUTHORIZED);
}
and pojo class as this:
package com.ravionics.user.entity;
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;
#Entity
#Table(name="users")
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="user_Id")
private int userId;
#Column(name="user_Name")
private String userName;
#Column(name="user_Email")
private String userEmail;
#Column(name="user_Password")
private String userPassword;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
userEmail = userEmail;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
userPassword = userPassword;
}
}

Hibernate connecting table unique on columns problem

I have problem with hibernate because he creates connecting table (I don't know why will be nice if can tell me where and why), and what is worst he using unique on columns and i cant add more then one user with the same role.
Whole project: https://github.com/dextep/sms/tree/master/src/main/java/pl/popiel/sms
Database look
User.class
package pl.popiel.sms.model.user;
import org.hibernate.validator.constraints.UniqueElements;
import javax.persistence.*;
import javax.validation.constraints.Email;
import java.util.Set;
#Entity
#Table(name="sms_users")
#SequenceGenerator(name = "sms_users_seq", sequenceName = "sms_users_seq", allocationSize = 1)
public class User {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sms_users_seq")
private long id;
#Email
private String email;
private String password;
private String firstName;
private String lastName;
#Column(name="mobile_nr")
private String mobileNumber;
#ElementCollection(targetClass=Role.class)
private Set<Role> roles;
public String getFullName() {
return firstName != null ? firstName.concat(" ").concat(lastName) : "";
}
public User() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 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 getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Role.class
package pl.popiel.sms.model.user;
import org.hibernate.validator.constraints.UniqueElements;
import org.springframework.stereotype.Indexed;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="sms_roles")
#SequenceGenerator(name = "sms_roles_seq", sequenceName = "sms_roles_seq", allocationSize = 1)
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sms_roles_seq")
private long id;
private String role;
public Role() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
I didn't notice that I miss the #ManyToMany annotation at 'roles' in User class.
Solve:
#ManyToMany
private Set<Role> roles;

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);

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 ...

Resources