How to Manage Entity relatinships with hibernate in Google App engine - spring

When I am having only 1 onetoMany relation code works fine. When I declare more that 1 #onetomany relation in an entity its breaks saying : org.hibernate.exception.SQLGrammarException: Unknown column 'userregist0_.jdoDetachedState' in 'field list' How this can be managed MY entity class is: package com.bullbeardevice.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
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.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The persistent class for the user_registration database table.
*
*/
#Entity
#Table(name = "user_registration")
#NamedQuery(name = "UserRegistration.findAll", query = "SELECT u FROM UserRegistration u")
#PersistenceCapable(identityType=IdentityType.APPLICATION, detachable="false")
public class UserRegistration implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_Registration_Id")
private String userRegistrationId;
#Column(name = "account_Status")
private int accountStatus;
#Column(name = "created_By")
private String createdBy;
#Column(name = "created_On")
#Temporal(TemporalType.TIMESTAMP)
private Date createdOn;
#Column(name = "email_Address")
private String emailAddress;
#Column(name = "expiry_Date")
#Temporal(TemporalType.TIMESTAMP)
private Date expiryDate;
#ManyToOne
#JoinColumn(name = "Group_Master_Id")
private GroupMaster groupMaster;
#Column(name = "modified_By")
private String modifiedBy;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modified_On")
private Date modifiedOn;
#Column(name = "user_password")
private String password;
#Column(name = "permissions")
private int permissions;
// bi-directional many-to-one association to Chat
#OneToMany(mappedBy = "userRegistration")
private List<Chat> chats;
// bi-directional many-to-one association to Coupon
#OneToMany(mappedBy = "userRegistration")
private List<Coupon> coupons;
// bi-directional many-to-one association to DeviceDetail
#OneToMany(mappedBy = "userRegistration")
private List<DeviceDetail> deviceDetails;
// bi-directional many-to-one association to Portfolio
#OneToMany(mappedBy = "userRegistration")
private List<Portfolio> portfolios;
// bi-directional many-to-one association to UserDetail
#OneToMany(mappedBy = "userRegistration")
private List<UserDetail> userDetails;
// bi-directional many-to-one association to UserLoginDetail
#OneToMany(mappedBy = "userRegistration")
private List<UserLoginDetail> userLoginDetails;
// bi-directional many-to-one association to UserRoleMaster
#ManyToOne
#JoinColumn(name = "User_Role_Master_Id")
private UserRoleMaster userRoleMaster;
// bi-directional many-to-one association to Watch
#OneToMany(mappedBy = "userRegistration")
private List<Watch> watches;
public UserRegistration() {
}
/**
* #return the userRegistrationId
*/
public String getUserRegistrationId() {
return userRegistrationId;
}
/**
* #param userRegistrationId
* the userRegistrationId to set
*/
public void setUserRegistrationId(String userRegistrationId) {
this.userRegistrationId = userRegistrationId;
}
/**
* #return the accountStatus
*/
public int getAccountStatus() {
return accountStatus;
}
/**
* #param accountStatus
* the accountStatus to set
*/
public void setAccountStatus(int accountStatus) {
this.accountStatus = accountStatus;
}
/**
* #return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* #param createdBy
* the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* #return the createdOn
*/
public Date getCreatedOn() {
return createdOn;
}
/**
* #param createdOn
* the createdOn to set
*/
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
/**
* #return the emailAddress
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* #param emailAddress
* the emailAddress to set
*/
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
/**
* #return the expiryDate
*/
public Date getExpiryDate() {
return expiryDate;
}
/**
* #param expiryDate
* the expiryDate to set
*/
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
/**
* #return the groupMaster
*/
public GroupMaster getGroupMaster() {
return groupMaster;
}
/**
* #param groupMaster
* the groupMaster to set
*/
public void setGroupMaster(GroupMaster groupMaster) {
this.groupMaster = groupMaster;
}
/**
* #return the modifiedBy
*/
public String getModifiedBy() {
return modifiedBy;
}
/**
* #param modifiedBy
* the modifiedBy to set
*/
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
/**
* #return the modifiedOn
*/
public Date getModifiedOn() {
return modifiedOn;
}
/**
* #param modifiedOn
* the modifiedOn to set
*/
public void setModifiedOn(Date modifiedOn) {
this.modifiedOn = modifiedOn;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #return the permissions
*/
public int getPermissions() {
return permissions;
}
/**
* #param permissions
* the permissions to set
*/
public void setPermissions(int permissions) {
this.permissions = permissions;
}
/**
* #return the chats
*/
public List<Chat> getChats() {
return chats;
}
/**
* #param chats
* the chats to set
*/
public void setChats(List<Chat> chats) {
this.chats = chats;
}
public Chat addChat(Chat chat) {
getChats().add(chat);
chat.setUserRegistration(this);
return chat;
}
public Chat removeChat(Chat chat) {
getChats().remove(chat);
chat.setUserRegistration(null);
return chat;
}
public List<Coupon> getCoupons() {
return this.coupons;
}
public void setCoupons(List<Coupon> coupons) {
this.coupons = coupons;
}
public Coupon addCoupon(Coupon coupon) {
getCoupons().add(coupon);
coupon.setUserRegistration(this);
return coupon;
}
public Coupon removeCoupon(Coupon coupon) {
getCoupons().remove(coupon);
coupon.setUserRegistration(null);
return coupon;
}
public List<DeviceDetail> getDeviceDetails() {
return this.deviceDetails;
}
public void setDeviceDetails(List<DeviceDetail> deviceDetails) {
this.deviceDetails = deviceDetails;
}
public DeviceDetail addDeviceDetail(DeviceDetail deviceDetail) {
getDeviceDetails().add(deviceDetail);
deviceDetail.setUserRegistration(this);
return deviceDetail;
}
public DeviceDetail removeDeviceDetail(DeviceDetail deviceDetail) {
getDeviceDetails().remove(deviceDetail);
deviceDetail.setUserRegistration(null);
return deviceDetail;
}
public List<Portfolio> getPortfolios() {
return this.portfolios;
}
public void setPortfolios(List<Portfolio> portfolios) {
this.portfolios = portfolios;
}
public Portfolio addPortfolio(Portfolio portfolio) {
getPortfolios().add(portfolio);
portfolio.setUserRegistration(this);
return portfolio;
}
public Portfolio removePortfolio(Portfolio portfolio) {
getPortfolios().remove(portfolio);
portfolio.setUserRegistration(null);
return portfolio;
}
public List<UserDetail> getUserDetails() {
return this.userDetails;
}
public void setUserDetails(List<UserDetail> userDetails) {
this.userDetails = userDetails;
}
public UserDetail addUserDetail(UserDetail userDetail) {
getUserDetails().add(userDetail);
userDetail.setUserRegistration(this);
return userDetail;
}
public UserDetail removeUserDetail(UserDetail userDetail) {
getUserDetails().remove(userDetail);
userDetail.setUserRegistration(null);
return userDetail;
}
public List<UserLoginDetail> getUserLoginDetails() {
return this.userLoginDetails;
}
public void setUserLoginDetails(List<UserLoginDetail> userLoginDetails) {
this.userLoginDetails = userLoginDetails;
}
public UserLoginDetail addUserLoginDetail(UserLoginDetail userLoginDetail) {
getUserLoginDetails().add(userLoginDetail);
userLoginDetail.setUserRegistration(this);
return userLoginDetail;
}
public UserLoginDetail removeUserLoginDetail(UserLoginDetail userLoginDetail) {
getUserLoginDetails().remove(userLoginDetail);
userLoginDetail.setUserRegistration(null);
return userLoginDetail;
}
public UserRoleMaster getUserRoleMaster() {
return this.userRoleMaster;
}
public void setUserRoleMaster(UserRoleMaster userRoleMaster) {
this.userRoleMaster = userRoleMaster;
}
public List<Watch> getWatches() {
return this.watches;
}
public void setWatches(List<Watch> watches) {
this.watches = watches;
}
public Watch addWatch(Watch watch) {
getWatches().add(watch);
watch.setUserRegistration(this);
return watch;
}
public Watch removeWatch(Watch watch) {
getWatches().remove(watch);
watch.setUserRegistration(null);
return watch;
}
}
Please help. Thanks in advance!

With app-engine, you don't need hibernate. Most JPA annotations that you use with hibernate, are natively supported in app-engine. I believe you should not be mixing JDO (javax.jdo) and JPA(javax.persistence).

Related

ERROR: null value in column "album_id" of relation "songs" violates not-null constraint

The entity classes are as given below
I am not sure if this is problem with how Hibernate or Spring Data understands my input. In my project on backend I am using Java + Spring Data + Hibernate + PostgreSQL.
I am able to get and delete data from the database but not add to it.
//AlbumEntity
``
#Entity
#Table(name = "albums")
public class AlbumEntity extends ApplicationPersistenceEntity implements Album {
#Id
#Column(name = "album_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long albumId;
#Column(name = "NAME")
private String albumName;
#Column(name = "Genre")
private String genre;
#ManyToOne(cascade = CascadeType.PERSIST, optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "singer_id", nullable = false)
// #NotFound(action = NotFoundAction.IGNORE)
private SingerEntity singer;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "album")
private List<SongEntity> songs;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public AlbumEntity() {
}
/**
* The constructor.
*
* #param albumId
* #param albumName
* #param genre
* #param singer
* #param songs
*/
public AlbumEntity(long albumId, String albumName, String genre, SingerEntity singer, List<SongEntity> songs) {
super();
this.albumId = albumId;
this.albumName = albumName;
this.genre = genre;
this.singer = singer;
this.songs = songs;
}
/**
* #return albumId
*/
#Override
public long getAlbumId() {
return this.albumId;
}
/**
* #param albumId new value of {#link #getalbumId}.
*/
#Override
public void setAlbumId(long albumId) {
this.albumId = albumId;
}
/**
* #return albumName
*/
#Override
public String getAlbumName() {
return this.albumName;
}
/**
* #param albumName new value of {#link #getalbumName}.
*/
#Override
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
/**
* #return genre
*/
#Override
public String getGenre() {
return this.genre;
}
/**
* #param genre new value of {#link #getgenre}.
*/
#Override
public void setGenre(String genre) {
this.genre = genre;
}
/**
* #return singer
*/
public SingerEntity getSinger() {
return this.singer;
}
/**
* #param singer new value of {#link #getsinger}.
*/
public void setSinger(SingerEntity singer) {
this.singer = singer;
}
/**
* #return songs
*/
public List<SongEntity> getSongs() {
return this.songs;
}
/**
* #param songs new value of {#link #getsongs}.
*/
public void setSongs(List<SongEntity> songs) {
this.songs = songs;
}
#Override
#Transient
public Long getSingerId() {
if (this.singer == null) {
return null;
}
return this.singer.getId();
}
#Override
public void setSingerId(Long singerId) {
if (singerId == null) {
this.singer = null;
} else {
SingerEntity singerEntity = new SingerEntity();
singerEntity.setId(singerId);
this.singer = singerEntity;
}
}
}
//Song Entity
#Entity
#Table(name = "songs")
public class SongEntity extends ApplicationPersistenceEntity implements Song {
#Id
#Column(name = "song_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long songId;
#Column(name = "Title")
private String title;
#Column(name = "Content")
private String content;
#ManyToOne(cascade = CascadeType.PERSIST, optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "singer_id", nullable = false)
private SingerEntity singer;
#ManyToOne(cascade = CascadeType.PERSIST, optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "album_id")
private AlbumEntity album;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public SongEntity() {
}
/**
* The constructor.
*
* #param songId
* #param title
* #param content
* #param singer
* #param album
*/
public SongEntity(long songId, String title, String content, SingerEntity singer, AlbumEntity album) {
super();
this.songId = songId;
this.title = title;
this.content = content;
this.singer = singer;
this.album = album;
}
/**
* #return songId
*/
#Override
public long getSongId() {
return this.songId;
}
/**
* #param songId new value of {#link #getsongId}.
*/
#Override
public void setSongId(long songId) {
this.songId = songId;
}
/**
* #return title
*/
#Override
public String getTitle() {
return this.title;
}
/**
* #param title new value of {#link #gettitle}.
*/
#Override
public void setTitle(String title) {
this.title = title;
}
/**
* #return content
*/
#Override
public String getContent() {
return this.content;
}
/**
* #param content new value of {#link #getcontent}.
*/
#Override
public void setContent(String content) {
this.content = content;
}
/**
* #return singer
*/
public SingerEntity getSinger() {
return this.singer;
}
/**
* #param singer new value of {#link #getsinger}.
*/
public void setSinger(SingerEntity singer) {
this.singer = singer;
}
/**
* #return album
*/
public AlbumEntity getAlbum() {
return this.album;
}
/**
* #param album new value of {#link #getalbum}.
*/
public void setAlbum(AlbumEntity album) {
this.album = album;
}
#Override
#Transient
public Long getSingerId() {
if (this.singer == null) {
return null;
}
return this.singer.getId();
}
#Override
public void setSingerId(Long singerId) {
if (singerId == null) {
this.singer = null;
} else {
SingerEntity singerEntity = new SingerEntity();
singerEntity.setId(singerId);
this.singer = singerEntity;
}
}
#Override
#Transient
public Long getAlbumId() {
if (this.album == null) {
return null;
}
return this.album.getId();
}
#Override
public void setAlbumId(Long albumId) {
if (albumId == null) {
this.album = null;
} else {
AlbumEntity albumEntity = new AlbumEntity();
albumEntity.setId(albumId);
this.album = albumEntity;
}
}
}
singer entity
#Entity
#Table(name = "singers")
public class SingerEntity extends ApplicationPersistenceEntity implements Singer {
#Id
#Column(name = "singer_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long singerId;
#Column(name = "First_NAME")
private String firstname;
#Column(name = "Last_NAME")
private String lastname;
#Column(name = "Gender")
private String gender;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "singer")
private List<SongEntity> songs;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "singer")
private List<AlbumEntity> albums;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public SingerEntity() {
}
/**
* The constructor.
*
* #param singerId
* #param firstname
* #param lastname
* #param gender
* #param songs
* #param albums
*/
public SingerEntity(long singerId, String firstname, String lastname, String gender, List<SongEntity> songs,
List<AlbumEntity> albums) {
super();
this.singerId = singerId;
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
this.songs = songs;
this.albums = albums;
}
/**
* #return singerId
*/
#Override
public long getSingerId() {
return this.singerId;
}
/**
* #param singerId new value of {#link #getsingerId}.
*/
#Override
public void setSingerId(long singerId) {
this.singerId = singerId;
}
/**
* #return firstname
*/
#Override
public String getFirstname() {
return this.firstname;
}
/**
* #param firstname new value of {#link #getfirstname}.
*/
#Override
public void setFirstname(String firstname) {
this.firstname = firstname;
}
/**
* #return lastname
*/
#Override
public String getLastname() {
return this.lastname;
}
/**
* #param lastname new value of {#link #getlastname}.
*/
#Override
public void setLastname(String lastname) {
this.lastname = lastname;
}
/**
* #return gender
*/
#Override
public String getGender() {
return this.gender;
}
/**
* #param gender new value of {#link #getgender}.
*/
#Override
public void setGender(String gender) {
this.gender = gender;
}
/**
* #return songs
*/
public List<SongEntity> getSongs() {
return this.songs;
}
/**
* #param songs new value of {#link #getsongs}.
*/
public void setSongs(List<SongEntity> songs) {
this.songs = songs;
}
/**
* #return albums
*/
public List<AlbumEntity> getAlbums() {
return this.albums;
}
/**
* #param albums new value of {#link #getalbums}.
*/
public void setAlbums(List<AlbumEntity> albums) {
this.albums = albums;
}
}
While checking Post endpoint
"modificationCounter": 2,
"id": 302,
"songId": 302,
"title": "As it was",
"content": "songs",
"singer_id": 201,
"album_id": 101
I am giving this data...still there is this error
org.postgresql.util.PSQLException: ERROR: null value in column "album_id" of relation "songs" violates not-null constraint
Detail: Failing row contains (302, 2, 302, As it was, songs, null, null).
This one keeps on coming... I guess you are using your entities as DTOs. DON'T
The problem is that you send an ID for albumID and singerID which are objects in Java.
For this to work, create a DTO that maps your fields and lookup the IDs in your database then create your Song Entity with those. Also, you need to map back the song in your album and singer for JPA to work correctly.

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 Security: authentication userdao is null

I have set up JSF with Spring Security.
I narrowed the problem down to the createCriteria method which returns nothing.
Any ideas?
Why does my userdao return null?
I have a MyUserDetailsService:
public class MyUserDetailsService implements UserDetailsService, Serializable {
/**
*
*/
private static final long serialVersionUID = 1864276199817921495L;
private UserDao userDao;
#Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
bla.bla.bla.model.User user = userDao.getUser(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getPermissions());
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(bla.bla.bla.model.User user,
List<GrantedAuthority> authorities) {
return new User(user.getUsername(),
user.getPassword(), user.getEnabled(),
true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<Permission> Permissions) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (Permission permission : Permissions) {
setAuths.add(new SimpleGrantedAuthority(permission.getPermission()));
}
List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
return Result;
}
/*
* Get the UserDao
*/
public UserDao getUserDao() {
return userDao;
}
/*
* Set the userDao
*/
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
I am able to get the final String username and pass it to userDao.getUser(username) but my method returns null for the user object so that when I access a method I get the following error:
[ERROR] org.springframework.security.web.authentication.UsernamePasswordAuthenticationFi lter:226 - An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException
This is what is called by getuser(username):
public GenericDaoImpl(final Class<T> type) {
super();
this.type = type;
}
#SuppressWarnings("unchecked")
public T getBySingleValue(String field, Object value){
Session session = sessionFactory.getCurrentSession();
try{
if(!session.getTransaction().isActive())
session.beginTransaction();
//Create a new Criteria instance, for the given entity class
//Executes a query against a particular persistent class
Criteria criteria = session.createCriteria(type);
criteria.add(Restrictions.eq(field, value));
T object = (T)criteria.uniqueResult();
return object;
} catch (Exception e){
System.out.println("ERROR");
e.printStackTrace();
return null;
} finally {
if(session.getTransaction().isActive())
session.getTransaction().commit();
}
}
Criteria criteria = session.createCriteria(type); returns null when it shouldn't. No hibernate sql statements are printed out.
My JPA mappings are here:
#Entity
#Table(name="users")
public class User {
private Integer id;
private String username;
private String firstname;
private String lastname;
private String password;
private Set<Permission> permissions = new HashSet<Permission>(0);
/**
* Default Constructor
*/
public User(){
}
public User(String username, String firstname,
String lastname,String password){
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
}
public User(String username, String firstname,
String lastname,String password,
Set<Permission> permissions) {
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.permissions = permissions;
}
/**Get the id
* #return the id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
/**Set the id
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**Get the username
* #return the username
*/
#Column(name="username", unique=true, nullable = false, length=25)
public String getUsername() {
return this.username;
}
/**Set the username
* #param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* #return the firstname
*/
#Column(name="firstname", nullable = false, length=20)
public String getFirstName() {
return this.firstname;
}
/**
* #param firstname the firstname to set
*/
public void setFirstName(String firstname) {
this.firstname = firstname;
}
/**
* #return the lastname
*/
#Column(name="lastname", nullable = false, length=20)
public String getLastName() {
return this.lastname;
}
/**
* #param lastname the lastname to set
*/
public void setLastName(String lastname) {
this.lastname = lastname;
}
/**
* #return the password
*/
#Column(name="password", nullable = false, length=60)
public String getPassword() {
return this.password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #return the userPermissions
*/
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="user_permission",
joinColumns = #JoinColumn(name="user_id", nullable=false),
inverseJoinColumns = #JoinColumn(name="permission_id",nullable=false))
public Set<Permission> getPermissions() {
return this.permissions;
}
/**
* #param userPermissions the userPermissions to set
*/
public void setPermissions(Set<Permission> userPermissions) {
this.permissions = userPermissions;
}
}
#Entity
#Table(name="permission")
public class Permission {
private Integer id;
private String permission;
private String description;
private Set<User> users = new HashSet<User>(0);
/**
* Default constructor
*/
public Permission(){
}
public Permission(String permission, String description,
Set<User> users) {
this.permission = permission;
this.description = description;
this.users = users;
}
/**
* #return the id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
/**
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* #return the permission
*/
#Column(name = "permission", unique = true, nullable = false, length = 50)
public String getPermission() {
return this.permission;
}
/**
* #param permission the permission to set
*/
public void setPermission(String permission) {
this.permission = permission;
}
/**
* #return the description
*/
#Column(name = "description", length = 150)
public String getDescription() {
return this.description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the users
*/
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "permissions")
public Set<User> getUsers() {
return this.users;
}
/**
* #param users the users to set
*/
public void setUsers(Set<User> users) {
this.users = users;
}
}
MY userDAO and MyUserServiceDetail is defined in xml file:
<bean id="userDao" class="bla.bla.bla.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myUserDetailsService"
class="bla.bla.bla.service.MyUserDetailsService">
<property name="userDao" ref="userDao" />
</bean>
I think my JPA mappings could be wrong...
Figured it out:
I added to hibernate session configuration:
<property name="annotatedClasses">
<list>
<value>bla.blah.bla.User</value>
<value>bla.blah.bla.model.UserOrganization</value>
<value>bla.blah.bla.model.Permission</value>
</list>
</property>

Updating null value for foreign key

I am working with JPA and I am trying to insert foreign key value its working fine but during modifying it is updating null values..
Please Refer following code
package com.bcits.bfm.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="JOB_CALENDER")
public class JobCalender implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int jobCalenderId;
private int scheduleType;
private String title;
private String description;
private String recurrenceRule;
private String recurrenceException;
private int recurrenceId;
private boolean isAllDay;
private Date start;
private Date end;
private String jobNumber;
private String jobGroup;
private int expectedDays;
private String jobPriority;
private String jobAssets;
private MaintainanceTypes maintainanceTypes;
private MaintainanceDepartment departmentName;
private JobTypes jobTypes;
#Id
#Column(name="JOB_CALENDER_ID")
#SequenceGenerator(name = "JOB_CALENDER_SEQUENCE", sequenceName = "JOB_CALENDER_SEQUENCE")
#GeneratedValue(generator = "JOB_CALENDER_SEQUENCE")
public int getJobCalenderId() {
return jobCalenderId;
}
public void setJobCalenderId(int jobCalenderId ) {
this.jobCalenderId = jobCalenderId ;
}
#Column(name="SCHEDULE_TYPE")
public int getScheduleType() {
return scheduleType;
}
public void setScheduleType(int scheduleType) {
this.scheduleType = scheduleType;
}
#Column(name="START_DATE")
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
#Column(name="END_DATE")
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
#Column(name="Title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="RECURRENCE_RULE")
public String getRecurrenceRule() {
return recurrenceRule;
}
public void setRecurrenceRule(String recurrenceRule) {
this.recurrenceRule = recurrenceRule;
}
#Column(name="IS_ALL_DAY")
public boolean getIsAllDay() {
return isAllDay;
}
public void setIsAllDay(boolean isAllDay) {
this.isAllDay = isAllDay;
}
#Column(name="RECURENCE_EXCEPTION")
public String getRecurrenceException() {
return recurrenceException;
}
public void setRecurrenceException(String recurrenceException) {
this.recurrenceException = recurrenceException;
}
#Column(name="RECURRENCE_ID")
public int getRecurrenceId() {
return recurrenceId;
}
public void setRecurrenceId(int recurrenceId) {
this.recurrenceId = recurrenceId;
}
/*Custom Columns*/
#Column(name = "JOB_NUMBER", nullable = false, length = 45)
public String getJobNumber() {
return this.jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
#Column(name = "JOB_GROUP", nullable = false, length = 45)
public String getJobGroup() {
return this.jobGroup;
}
public void setJobGroup(String jobGroup) {
this.jobGroup = jobGroup;
}
#Column(name = "EXPECTED_DAYS", nullable = false, precision = 11, scale = 0)
public int getExpectedDays() {
return this.expectedDays;
}
public void setExpectedDays(int expectedDays) {
this.expectedDays = expectedDays;
}
#Column(name = "JOB_PRIORITY", nullable = false, length = 45)
public String getJobPriority() {
return this.jobPriority;
}
public void setJobPriority(String jobPriority) {
this.jobPriority = jobPriority;
}
#Column(name = "JOB_ASSETS", nullable = false, length = 4000)
public String getJobAssets() {
return this.jobAssets;
}
public void setJobAssets(String jobAssets) {
this.jobAssets = jobAssets;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_DEPT_ID",referencedColumnName="MT_DP_IT",nullable = false)
public MaintainanceDepartment getMaintainanceDepartment() {
return this.departmentName;
}
public void setMaintainanceDepartment(
MaintainanceDepartment departmentName) {
this.departmentName = departmentName;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_TYPE_ID",referencedColumnName="JT_ID",nullable = false)
public JobTypes getJobTypes() {
return this.jobTypes;
}
public void setJobTypes(JobTypes jobTypes) {
this.jobTypes = jobTypes;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "MAINTAINANCE_TYPE_ID",nullable = false)
public MaintainanceTypes getMaintainanceTypes() {
return this.maintainanceTypes;
}
public void setMaintainanceTypes(MaintainanceTypes maintainanceTypes) {
this.maintainanceTypes = maintainanceTypes;
}
}
And Parent Table Is
package com.bcits.bfm.model;
import java.sql.Timestamp;
import java.util.HashSet;
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.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* MaintainanceTypes entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "MAINTAINANCE_TYPES")
public class MaintainanceTypes implements java.io.Serializable {
private static final long serialVersionUID = 1L;
// Fields
private int mtId;
private String maintainanceType;
private String description;
private Timestamp mtDt;
private String createdBy;
private String lastUpdatedBy;
private Timestamp lastUpdatedDt;
private Set<JobCards> jobCardses = new HashSet<JobCards>(0);
private Set<JobCalender> jobCalenders = new HashSet<JobCalender>(0);
// Constructors
/** default constructor */
public MaintainanceTypes() {
}
/** minimal constructor */
public MaintainanceTypes(int mtId, String maintainanceType, Timestamp mtDt) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.mtDt = mtDt;
}
/** full constructor */
public MaintainanceTypes(int mtId, String maintainanceType,
String description, Timestamp mtDt, String createdBy,
String lastUpdatedBy, Timestamp lastUpdatedDt,
Set<JobCards> jobCardses) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.description = description;
this.mtDt = mtDt;
this.createdBy = createdBy;
this.lastUpdatedBy = lastUpdatedBy;
this.lastUpdatedDt = lastUpdatedDt;
this.jobCardses = jobCardses;
}
// Property accessors
#Id
#Column(name = "MT_ID", unique = true, nullable = false, precision = 11, scale = 0)
#SequenceGenerator(name = "MAINTENANCE_TYPES_SEQ", sequenceName = "MAINTENANCE_TYPES_SEQ")
#GeneratedValue(generator = "MAINTENANCE_TYPES_SEQ")
public int getMtId() {
return this.mtId;
}
public void setMtId(int mtId) {
this.mtId = mtId;
}
#Column(name = "MAINTAINANCE_TYPE", nullable = false, length = 20)
public String getMaintainanceType() {
return this.maintainanceType;
}
public void setMaintainanceType(String maintainanceType) {
this.maintainanceType = maintainanceType;
}
#Column(name = "DESCRIPTION", length = 200)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "MT_DT", nullable = false, length = 11)
public Timestamp getMtDt() {
return this.mtDt;
}
public void setMtDt(Timestamp mtDt) {
this.mtDt = mtDt;
}
#Column(name = "CREATED_BY", length = 45)
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "LAST_UPDATED_BY", length = 45)
public String getLastUpdatedBy() {
return this.lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
#Column(name = "LAST_UPDATED_DT", length = 11)
public Timestamp getLastUpdatedDt() {
return this.lastUpdatedDt;
}
public void setLastUpdatedDt(Timestamp lastUpdatedDt) {
this.lastUpdatedDt = lastUpdatedDt;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCards> getJobCardses() {
return this.jobCardses;
}
public void setJobCardses(Set<JobCards> jobCardses) {
this.jobCardses = jobCardses;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCalender> getJobCalenders() {
return this.jobCalenders;
}
public void setJobCalenders(Set<JobCalender> jobCalenders) {
this.jobCalenders = jobCalenders;
}
}
I am calling below method to Update
public void Update(JobCalender jobCalender) {
update(jobCalender); //update() is generic method
}
public T update(final T t) {
BfmLogger.logger.info("updating "+t+" instance");
try {
T result = this.entityManager.merge(t);
BfmLogger.logger.info("update successful");
return result;
} catch (RuntimeException re) {
BfmLogger.logger.error("update failed", re);
throw re;
}
}
My Controller Code
#RequestMapping(value = "/index/create", method = RequestMethod.POST)
public #ResponseBody List<?> create(#RequestBody Map<String, Object>model,#ModelAttribute JobCalender jobCalender,BindingResult bindingResult, HttpServletRequest request) throws ParseException {
jobCalender.setDescription((String)model.get("description"));
jobCalender.setTitle((String)model.get("title"));
SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-M-dd'T'HH:mm:ss.SSS'Z'");
iso8601.setTimeZone(TimeZone.getTimeZone("UTC"));
jobCalender.setStart(iso8601.parse((String)model.get("start")));
jobCalender.setEnd(iso8601.parse((String)model.get("end")));
jobCalender.setIsAllDay((boolean) model.get("isAllDay"));
jobCalender.setRecurrenceRule((String)model.get("recurrenceRule"));
jobCalender.setRecurrenceException((String)model.get("recurrenceException"));
if(model.get("recurrenceId")!=null)
jobCalender.setRecurrenceId((Integer)model.get("recurrenceId"));
jobCalender.setScheduleType(Integer.parseInt(model.get("scheduleType").toString()));
jobCalender.setJobNumber((String) model.get("jobNumber"));
jobCalender.setDescription((String) model.get("description"));
jobCalender.setJobGroup((String) model.get("jobGroup"));
jobCalender.setMaintainanceDepartment(maintainanceDepartmentService.find(Integer.parseInt(model.get("departmentName").toString())));
jobCalender.setMaintainanceTypes(maintainanceTypesService.find(Integer.parseInt(model.get("maintainanceTypes").toString())));
jobCalender.setJobTypes(jobTypesService.find(Integer.parseInt(model.get("jobTypes").toString())));
jobCalender.setJobPriority((String) model.get("jobPriority"));
String ids="";
#SuppressWarnings("unchecked")
List<Map<String, Object>> listAssets = (ArrayList<Map<String, Object>>) model.get("assetName");// this is what you have already
for (Map<String, Object> map1 :listAssets) {
for (Map.Entry<String, Object> entry : map1.entrySet()) {
if(entry.getKey().equalsIgnoreCase("assetId")){
ids+=entry.getValue()+",";
}
}
}
jobCalender.setJobAssets(ids);
jobCalenderService.Update(jobCalender);
}
while Updating JOB_CALENDER Table it is Adding NULL Value For MAINTAINANCE_TYPE_ID Column
Please Help Me
Thank You
Regards
Manjunath Kotagi

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

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

Resources