OPEN JPA find() could not retrieve the value of the entity from my Database - spring

There is a weird scenario that I had encountered in my User log in program.
Insert the record.. Userid password etc.
Insert the record using merge();
Then close the IDE (Netbeans)
Open IDE Netbeans then start servers, start database connection.
Open the log in browser.
log in using the inserted record.
My program could not detect the record on the table.
When debugging, after the find() it would not populate my entity.. Maybe there is still another step to populate the entity?
LoginAction
package lotmovement.action;
import com.opensymphony.xwork2.ActionSupport;
import lotmovement.business.crud.RecordExistUserProfile;
import org.apache.commons.lang3.StringUtils;
public class LoginAction extends ActionSupport{
private String userName;
private RecordExistUserProfile recordExistUserProfile;
private String password;
#Override
public void validate(){
if(StringUtils.isEmpty(getUserName())){
addFieldError("userName","Username must not be blanks.");
}
else{
if(!recordExistUserProfile.checkrecordexist(getUserName())){
addFieldError("userName","Username don't exist.");
}
}
if(StringUtils.isEmpty(getPassword())){
addFieldError("password","Password must not be blanks.");
}
else{
if(!recordExistUserProfile.CheckPasswordCorrect(getUserName(), getPassword())){
addFieldError("userName","Password not correct");
}
}
}
public String execute(){
return SUCCESS;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public RecordExistUserProfile getRecordExistUserProfile() {
return recordExistUserProfile;
}
public void setRecordExistUserProfile(RecordExistUserProfile recordExistUserProfile) {
this.recordExistUserProfile = recordExistUserProfile;
}
}
Validator Program
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.crud;
import lotmovement.business.entity.UserProfile;
/**
*
* #author god-gavedmework
*/
public class RecordExistUserProfile {
private EntityStart entityStart;
private UserProfile userProfile;
public boolean checkrecordexist(String userId) {
entityStart.StartDbaseConnection();
entityStart.em.find(UserProfile.class, userId);
if (userId.equals(userProfile.getUserId())) {
return true;
} else {
return false;
}
}
public boolean CheckPasswordCorrect(String userId, String password) {
entityStart.StartDbaseConnection();
entityStart.em.find(UserProfile.class, userId);
if (password.equals(userProfile.getPassword())) {
return true;
} else {
return false; ---> It will step here.
}
}
public UserProfile getUserProfile() {
return userProfile;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
public EntityStart getEntityStart() {
return entityStart;
}
public void setEntityStart(EntityStart entityStart) {
this.entityStart = entityStart;
}
}
Entity
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.entity;
import java.io.Serializable;
import javax.persistence.*;
/**
*
* #author god-gavedmework
*/
#Entity(name = "USERPROFILE") //Name of the entity
public class UserProfile implements Serializable{
#Id //signifies the primary key
#Column(name = "USER_ID", nullable = false,length = 20)
private String userId;
#Column(name = "PASSWORD", nullable = false,length = 20)
private String password;
#Column(name = "FIRST_NAME", nullable = false,length = 20)
private String firstName;
#Column(name = "LAST_NAME", nullable = false,length = 50)
private String lastName;
#Column(name = "SECURITY_LEVEL", nullable = false,length = 4)
private int securityLevel;
#Version
#Column(name = "LAST_UPDATED_TIME")
private java.sql.Timestamp updatedTime;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 int getSecurityLevel() {
return securityLevel;
}
public void setSecurityLevel(int securityLevel) {
this.securityLevel = securityLevel;
}
public java.sql.Timestamp getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(java.sql.Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
}
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.crud;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import lotmovement.business.entity.UserProfile;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;
public class EntityStart {
EntityManagerFactory factory;
EntityManager em;
public void StartDbaseConnection()
{
factory = Persistence.createEntityManagerFactory("LotMovementPU");
em = factory.createEntityManager();
}
public void StartPopulateTransaction(Object entity){
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
em.merge(entity);
userTransaction.commit();
em.close();
}
public void CloseDbaseConnection(){
factory.close();
}
}
Using Trace as adviced, This is the log of the SQL
SELECT t0.LAST_UPDATED_TIME, t0.FIRST_NAME, t0.LAST_NAME, t0.PASSWORD, t0.SECURITY_LEVEL FROM USERPROFILE t0 WHERE t0.USER_ID = ? [params=(String) tok]
This is the record:
USER_ID FIRST_NAME LAST_NAME PASSWORD SECURITY_LEVEL LAST_UPDATED_TIME
tok 1 1 1 1 2012-12-13 08:46:48.802
Added Persistence.XML
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="LotMovementPU" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<non-jta-data-source/>
<class>lotmovement.business.entity.UserProfile</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:derby://localhost:1527/LotMovementDBase"/>
<property name="openjpa.ConnectionDriverName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="openjpa.ConnectionUserName" value="toksis"/>
<property name="openjpa.ConnectionPassword" value="bitoytoksis"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
</properties>
</persistence-unit>
</persistence>
I discovered the root cause of the problem. It is on how I instantiate the class in Spring Plugin.
When I change the find() statement to below, it will now work.
UserProfile up = entityStart.em.find(UserProfile.class, "tok");
But how can i initialize this one using Spring? codes below dont work?
private UserProfile userProfile;
...... some codes here.
entityStart.em.find(UserProfile.class, userId);
..... getter setter

The Root cause of the problem.
entityStart.em.find(UserProfile.class, userId); --> it should be
userProfile = entityStart.em.find(UserProfile.class, userId);

Related

Relationship CRUD API Spring Boot

I am creating a crud api with a many to many relationship betwen role and user. When i make a Get HTTP Request, i get the mesage below but When i delete all relationship and make findall on single table, it works percfecttly. Where do you think the problem is?
Error Message in postman
{
"timestamp": "2021-07-10T04:28:24.877+0000",
"status": 500,
"error": "Internal Server Error",
"message": "JSON mapping problem: java.util.ArrayList[0]->com.notyfyd.entity.User[\"roles\"]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.notyfyd.entity.User.roles, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.notyfyd.entity.User[\"roles\"])",
"path": "/user/all"
}
Role Entity
package com.notyfyd.entity;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "t_role")
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
#ManyToMany(targetEntity = User.class, mappedBy = "roles", cascade = {CascadeType.PERSIST, CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH})
private List<User> users;
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;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
User Entity
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "t_user")
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String mobile;
#Column(unique = true)
private String email;
#ManyToMany(targetEntity = Role.class, cascade = {CascadeType.PERSIST, CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH} )
#JoinTable(
name="t_user_roles",
joinColumns=
#JoinColumn( name="user_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="role_id", referencedColumnName="id"))
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;
}
}
here is the log error on MSSQL Server
2021-07-10 11:20:59.333 WARN 3124 --- [nio-6120-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: fdsa.edu.PNUFDSA.Model.AnneeAcademique.paiements, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: fdsa.edu.PNUFDSA.Model.AnneeAcademique.paiements, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->fdsa.edu.PNUFDSA.Model.AnneeAcademique["paiements"])]
the Entity is:
* "Visual Paradigm: DO NOT MODIFY THIS FILE!"
*
* This is an automatic generated file. It will be regenerated every time
* you generate persistence class.
*
* Modifying its content may cause the program not work, or your work may lost.
*/
/**
* Licensee:
* License Type: Evaluation
*/
package fdsa.edu.PNUFDSA.Model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
#Entity
#Data
//#org.hibernate.annotations.Proxy(lazy=false)
#Table(name="AnneeAcademique")
public class AnneeAcademique implements Serializable {
public AnneeAcademique() {
}
#Column(name="ID", nullable=false, length=10)
#Id
#GeneratedValue(generator="PNU_ANNEEACADEMIQUE_ID_GENERATOR")
#org.hibernate.annotations.GenericGenerator(name="PNU_ANNEEACADEMIQUE_ID_GENERATOR", strategy="native")
private int id;
#Column(name="Debut", nullable=true)
#Temporal(TemporalType.DATE)
private java.util.Date debut;
#Column(name="Fin", nullable=true)
#Temporal(TemporalType.DATE)
private java.util.Date fin;
#JsonIgnore
#ManyToMany(mappedBy="anneeAcademiques", targetEntity=fdsa.edu.PNUFDSA.Model.Cours.class)
#org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK})
#org.hibernate.annotations.LazyCollection(org.hibernate.annotations.LazyCollectionOption.TRUE)
private java.util.Set cours = new java.util.HashSet();
#JsonIgnore
#OneToMany(mappedBy="anneeAcademique", targetEntity=fdsa.edu.PNUFDSA.Model.Paiement.class)
#org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK})
#org.hibernate.annotations.LazyCollection(org.hibernate.annotations.LazyCollectionOption.TRUE)
private List paiements = new ArrayList();
private void setId(int value) {
this.id = value;
}
public int getId() {
return id;
}
public int getORMID() {
return getId();
}
public void setDebut(java.util.Date value) {
this.debut = value;
}
public java.util.Date getDebut() {
return debut;
}
public void setFin(java.util.Date value) {
this.fin = value;
}
public java.util.Date getFin() {
return fin;
}
public void setCours(java.util.Set value) {
this.cours = value;
}
public java.util.Set getCours() {
return cours;
}
public void setPaiements(List value) {
this.paiements = value;
}
public List getPaiements() {
return paiements;
}
public String toString() {
return String.valueOf(getId());
}
}
Are you returning that entity directly as json. Can add #JsonIgnore on below field.
#JsonIgnore
private List<Role> roles;
You can set fetch type to FetchType.EAGER on your many to many relations in your entities.
Try this and let me know what happened.

Spring tool suite: not-null property references a null or transient value

could you help me with this question?
I built a project on sts4. I am trying to let users register an account on Postman. The primary method I am testing is Put(PutMapping), which I wrote on sts4. I got the project initialized completely, but when I click send from Postman, I got errors like below.
not-null property references a null or transient value: com.appsdeveloperblog.app.ws.io.entity.UserEntity.firstName
The following is part of my project.
UserDetailsRequestModel, (for processing incoming requestbody)
public class UserDetailsRequestModel {
private String firstName;
private String lastName;
private String email;
private String 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;
}
}```
2. UserRest, (Class, which will be returned back to Postman)
```package com.appsdeveloperblog.app.ws.ui.model.response;
public class UserRest {
// public id, not auto increment key from database
private String userId;
private String firstName;
private String lastName;
private String email;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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;
}
}```
3. UserDTO
```package com.appsdeveloperblog.app.ws.shared.dto;
import java.io.Serializable;
public class UserDTO implements Serializable {
private static final long serialVersionUID = -5607842248454975055L;
// auto increment key from database
private long id;
// public user id, which could be returned back to application
private String userId;
private String firstName;
private String lastName;
private String email;
// clear text password
private String password;
// password which is encrypted, stored,
private String encryptedPassword;
private String emailVerificationToken;
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
UserEntity
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "users")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 5313493413859894403L;
// this Id is a primary key and auto incremented
// once a new record is inserted into database table
#Id
#GeneratedValue
private long id;
#Column(nullable = false)
private String userId;
#Column(nullable = false, length = 50)
private String firstName;
#Column(nullable = false, length = 50)
private String lastName;
#Column(nullable = false, length = 120)
private String email;
#Column(nullable = false)
private String encryptedPassword;
private String emailVerificationToken;
#Column(nullable = false)
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
UserServiceImpl
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.appsdeveloperblog.app.ws.UserRepository;
import com.appsdeveloperblog.app.ws.io.entity.UserEntity;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDTO;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserRepository userRepository;
#Override
public UserDTO createUser(UserDTO user) {
// (0) check whether the email already exist in database
if(userRepository.findByEmail(user.getEmail()) != null) {
throw new IllegalArgumentException("Email already exists.");
}
// 1. create an object UserEntity,
UserEntity userEntity = new UserEntity();
// 2. copy info from userDTO to userEntity
BeanUtils.copyProperties(user, userEntity);
// 3. encryptedPassword can't be got from user
// we have to assign value here for testing
userEntity.setEncryptedPassword("test");
// 4. the second data that is generated during this class is userID
userEntity.setUserId("testUserId");
// 5. now we can save userEntity into database,
// since it contains info from user, have to use userRepository
// after Auto-wired, we can use its methods
// use save method, we can save userEntity into database
UserEntity storedUserDetails = userRepository.save(userEntity);
// 6. we can return it back to RestController
// so we need an UserDTO object
UserDTO returnValue = new UserDTO();
BeanUtils.copyProperties(storedUserDetails, returnValue);
return returnValue;
}
}
UserController
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDTO;
import com.appsdeveloperblog.app.ws.ui.model.request.UserDetailsRequestModel;
import com.appsdeveloperblog.app.ws.ui.model.response.UserRest;
#RestController // to make this class receive requests from HTTP
#RequestMapping("users") // http://localhost:8080/users + methods
public class UserController {
#Autowired
UserService userService;
#GetMapping
public String getUser() {
return "get user was called";
}
#PostMapping
public UserRest createUser(#RequestBody UserDetailsRequestModel userDetails) {
// 1. instantiate a new object, which will be returned.
UserRest returnValue = new UserRest();
System.out.println(userDetails.getFirstname());
// 2. instantiate a new User Data transfer object,
// which could be shared across different layers
// we will populate this object with info we received from request body
UserDTO userDTO = new UserDTO();
// 3. use class BeanUtils class, which is from spring framework
// to copy properties from source object(userDetails) to our data transfer object
// so, we can populate info from request body into our data transfer object
// so, we have a data transfer object, which is populated info from request body
BeanUtils.copyProperties(userDetails, userDTO);
// 4.
// (1) userDTO, will be created at UI level, then be passed to service layer
// (2) service class will perform some additional business logic
// and generate some additional values, these values will be added to userDTO,
// (3) then userDTO will be used in business logic with a data layer
// to prepare an entity class, which will be stored in database
UserDTO createdUser = userService.createUser(userDTO);
// 5. populate returnValue object
// copy information from createdUser into returnValue
// other sensitive info, like password, should not be included
BeanUtils.copyProperties(createdUser, returnValue);
// 6. return, to mobile applications,or in here to Postman(HTTP client)
return returnValue;
}
#PutMapping
public String updateUser() {
return "update user was called";
}
#DeleteMapping
public String deleteUser() {
return "delete user was called";
}
}
Configuration on Postman
enter image description here
enter image description here
The Error I got
enter image description here
I spent a day on it. Help, please.
Try this:
#PutMapping
public String updateUser(#RequestBody) {
return "update user was called";
}

SpringBoot+Neo4J OGM update record

I am getting very weird problem when trying to update the record in database .Main Node is updating properly but Relationship not creating after deleting it.
I have Node with relationship in database i am trying to update it via this code
Role roleRecord = findByUuid(uuid);//Get Role Record
Role roleData = new Role();//Create a new role object and update values
roleData.setDescription(role.getDescription());
roleData.setUuid(roleRecord.getUuid());
roleData.setRoleName(roleRecord.getRoleName());
roleData.setLabels(updatedLabelRecord);
deleteRole(roleRecord);// Delete existing role from database
for (Labels label : dbRecord) { //Delete relationship Node
deleteLabel(label);
}
createRole(roleData);// Then Create role and Label with new Data set
This code creating Role record but not the Label Node(Which is a relationship),Relationship something like this
Role->FILTERS_ON->Label
EDIT 1-
Role is a Neo4j Entity
deleteRole is method
public void deleteRole(Role roleEntity) {
roleRepository.delete(roleEntity);
}
deleteLabel is a method
public void deleteLabel(com.nokia.nsw.uiv.uam.entities.Labels label) {
labelRepository.delete(label);
}
createRole is a method
public Role createRole(Role role) {
return roleRepository.save(role);
}
EDIT 2 -
Role Entity Class
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.Api;
#Api(
tags = "Role",
description = ""
)
#NodeEntity(label = "com.model.Role")
public class Role implements Serializable {
private static final long serialVersionUID = -8010543109475083169L;
private String roleName = null;
private String description = null;
// #Relationship(type = "HAS_ROLE", direction="INCOMING")
// private Tenant tenant;
#Relationship(type = "FILTERS_ON")
private List<Labels> labels = new ArrayList<>();
#JsonIgnore
private Long id;
#Id
#GeneratedValue(strategy = UivUuidStrategy.class)
#JsonProperty("id")
private String uuid;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// public Tenant getTenant() {
// return tenant;
// }
//
// public void setTenant(Tenant tenant) {
// this.tenant = tenant;
// }
public List<Labels> getLabels() {
return labels;
}
public void setLabels(List<Labels> labels) {
this.labels = labels;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Label Entity class
import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Properties;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
#NodeEntity(label = "com.model.role.Filter")
public class Labels implements Serializable {
private static final long serialVersionUID = 1L;
private String labelName;
#Properties
private Map<String, String> match;
private String access;
#JsonIgnore
private Long id;
#Id
#GeneratedValue(strategy = UivUuidStrategy.class)
#JsonProperty("id")
private String uuid;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public Map<String, String> getMatch() {
return match;
}
public void setMatch(Map<String, String> match) {
this.match = match;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public String getAccess() {
return access;
}
public void setAccess(String access) {
this.access = access;
}
#Override
public String toString() {
return "labelName : " + this.labelName;
}
#Override
public boolean equals(Object obj) {
return (obj instanceof Labels) && this.labelName.equals(((Labels) obj).getLabelName());
}
#Override
public int hashCode() {
return Objects.hash(labelName);
}
}

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

javax.el.MethodNotFoundException: Method not found:

Spring - Hibernate
Newbie here, can please somebody help me locate what i'm missing. I am trying to do a onetomany relationship of payee and payor. My issue is im getting this error:
javax.el.MethodNotFoundException: Method not found: class com.supportmanagement.model.Payee.getPayor()
javax.el.Util.findWrapper(Util.java:349)
javax.el.Util.findMethod(Util.java:211)
javax.el.BeanELResolver.invoke(BeanELResolver.java:150)
List.jsp
{payeelist} came from my controller via map.put("payeelist", payeeServices.getPayees());
...
<c:forEach items="${payeelist}" var="payee" varStatus="payeeindex">
<tr>
<td class="pad-0"> </td>
<td><c:out value="${payee.getCaseNumber()}" /></td>
<td><c:out value="${payee.getLastname()}" /></td>
<td><c:out value="${payee.getFirstname()}" /></td>
<td><c:out value="${payee.getMiddlename()}" /></td>
<td class="text-center"><a href="/SupportManager/payor/add?casenumber=${payee.getCaseNumber()}">
${payee.getPayor().getCaseNumber()}
</a></td>
<td class="text-center">ADD PAYMENT <i class="glyphicon glyphicon-envelope"></i> </td>
</tr>
</c:forEach>
...
Payee.java
package com.supportmanagement.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "payeeMaster")
public class Payee implements Serializable {
private static final long serialVersionUID = 5876875389515595233L;
#Id
#Column(name = "CaseNumber", unique = true, nullable = false)
private String CaseNumber;
#Column(name = "Firstname")
private String Firstname;
#Column(name = "Lastname")
private String Lastname;
#Column(name = "Middlename")
private String Middlename;
#Column(name = "Address1")
private String Address1;
#Column(name = "Address2")
private String Address2;
#Column(name = "City")
private String City;
#Column(name = "State")
private String State;
#Column(name = "Zip")
private String Zip;
#Column(name = "HomePhone")
private String HomePhone;
#Column(name = "MobilePhone")
private String MobilePhone;
#Column(name = "Active")
private int Active;
#Column(name = "Comments")
private String Comments;
#Column(name = "StateCode")
private String StateCode;
#Column(name = "PA")
private int PA;
#Column(name = "OSE")
private int OSE;
#Column(name = "Envelope")
private int Envelope;
#Column(name = "AccountNumber")
private String AccountNumber;
#Column(name = "DNumber")
private String DNumber;
#Column(name = "LastModified")
private Date LastModified;
#Column(name = "ModifiedBy")
private String ModifiedBy;
private List<Payor> payor;
#OneToMany(mappedBy="Payor", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name="CaseNumber")
public List<Payor> getPayor() {
return payor;
}
public void setPayor(List<Payor> payor) {
this.payor = payor;
}
public String getCaseNumber() {
return CaseNumber;
}
public void setCaseNumber(String caseNumber) {
CaseNumber = caseNumber;
}
public String getFirstname() {
return Firstname;
}
public void setFirstname(String firstname) {
Firstname = firstname;
}
public String getLastname() {
return Lastname;
}
public void setLastname(String lastname) {
Lastname = lastname;
}
public String getMiddlename() {
return Middlename;
}
public void setMiddlename(String middlename) {
Middlename = middlename;
}
public String getAddress1() {
return Address1;
}
public void setAddress1(String address1) {
Address1 = address1;
}
public String getAddress2() {
return Address2;
}
public void setAddress2(String address2) {
Address2 = address2;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getZip() {
return Zip;
}
public void setZip(String zip) {
Zip = zip;
}
public String getHomePhone() {
return HomePhone;
}
public void setHomePhone(String homePhone) {
HomePhone = homePhone;
}
public String getMobilePhone() {
return MobilePhone;
}
public void setMobilePhone(String mobilePhone) {
MobilePhone = mobilePhone;
}
public int getActive() {
return Active;
}
public void setActive(int active) {
Active = active;
}
public String getComments() {
return Comments;
}
public void setComments(String comments) {
Comments = comments;
}
public String getStateCode() {
return StateCode;
}
public void setStateCode(String stateCode) {
StateCode = stateCode;
}
public int getPA() {
return PA;
}
public void setPA(int pA) {
PA = pA;
}
public int getOSE() {
return OSE;
}
public void setOSE(int oSE) {
OSE = oSE;
}
public int getEnvelope() {
return Envelope;
}
public void setEnvelope(int envelope) {
Envelope = envelope;
}
public String getAccountNumber() {
return AccountNumber;
}
public void setAccountNumber(String accountNumber) {
AccountNumber = accountNumber;
}
public String getDNumber() {
return DNumber;
}
public void setDNumber(String dNumber) {
DNumber = dNumber;
}
public Date getLastModified() {
return LastModified;
}
public void setLastModified(Date lastModified) {
LastModified = lastModified;
}
public String getModifiedBy() {
return ModifiedBy;
}
public void setModifiedBy(String modifiedBy) {
ModifiedBy = modifiedBy;
}
}
Payor.java
package com.supportmanager.model;
import java.io.Serializable;
import java.util.List;
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;
#Entity
#Table(name = "payorMaster")
public class Payor implements Serializable {
private static final long serialVersionUID = -1896406931521329889L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PayorID")
private Integer PayorID;
#Column(name = "CaseNumber")
private String CaseNumber;
#Column(name = "PayorFirstname")
private String PayorFirstname;
#Column(name = "PayorLastname")
private String PayorLastname;
#Column(name = "PayorMiddlename")
private String PayorMiddlename;
#Column(name = "PayorAddress1")
private String PayorAddress1;
#Column(name = "PayorAddress2")
private String PayorAddress2;
#Column(name = "PayorCity")
private String PayorCity;
#Column(name = "PayorState")
private String PayorState;
#Column(name = "PayorZip")
private String PayorZip;
#Column(name = "PayorHomePhone")
private String PayorHomePhone;
#Column(name = "PayorMobilePhone")
private String PayorMobilePhone;
#Column(name = "PayorActive")
private int PayorActive;
#Column(name = "PayorComments")
private String PayorComments;
#ManyToOne
#JoinColumn(name="CaseNumber")
private List<Payee> payee;
public Integer getPayorID() {
return PayorID;
}
public void setPayorID(Integer payorID) {
PayorID = payorID;
}
public String getCaseNumber() {
return CaseNumber;
}
public void setCaseNumber(String caseNumber) {
CaseNumber = caseNumber;
}
public String getPayorFirstname() {
return PayorFirstname;
}
public void setPayorFirstname(String payorFirstname) {
PayorFirstname = payorFirstname;
}
public String getPayorLastname() {
return PayorLastname;
}
public void setPayorLastname(String payorLastname) {
PayorLastname = payorLastname;
}
public String getPayorMiddlename() {
return PayorMiddlename;
}
public void setPayorMiddlename(String payorMiddlename) {
PayorMiddlename = payorMiddlename;
}
public String getPayorAddress1() {
return PayorAddress1;
}
public void setPayorAddress1(String payorAddress1) {
PayorAddress1 = payorAddress1;
}
public String getPayorAddress2() {
return PayorAddress2;
}
public void setPayorAddress2(String payorAddress2) {
PayorAddress2 = payorAddress2;
}
public String getPayorCity() {
return PayorCity;
}
public void setPayorCity(String payorCity) {
PayorCity = payorCity;
}
public String getPayorState() {
return PayorState;
}
public void setPayorState(String payorState) {
PayorState = payorState;
}
public String getPayorZip() {
return PayorZip;
}
public void setPayorZip(String payorZip) {
PayorZip = payorZip;
}
public String getPayorHomePhone() {
return PayorHomePhone;
}
public void setPayorHomePhone(String payorHomePhone) {
PayorHomePhone = payorHomePhone;
}
public String getPayorMobilePhone() {
return PayorMobilePhone;
}
public void setPayorMobilePhone(String payorMobilePhone) {
PayorMobilePhone = payorMobilePhone;
}
public int getPayorActive() {
return PayorActive;
}
public void setPayorActive(int payorActive) {
PayorActive = payorActive;
}
public String getPayorComments() {
return PayorComments;
}
public void setPayorComments(String payorComments) {
PayorComments = payorComments;
}
}
ApplicationContext.xml
....
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.supportmanagement.model" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="show_sql">true</prop>
<prop key="enable_lazy_load_no_trans">true</prop>
<prop key="default_schema">SupportManagerDB</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.supportmanagement.model.Payee</value>
<value>com.supportmanagement.model.Payor</value>
</list>
</property>
</bean>
....
In you jsp page you use:
${payee.getPayor().getCaseNumber()}
Now.. getPayor() returns a List<Payor> and a List does not have the getCaseNumber() method.
You can get a certain Payor from the list and then invoke the method:
${payee.payor[index].caseNumber}
Where index is a hardcode value or a variable.

Resources