Hibernate related object not hydrated - java

Please see code below. DeviceDAO, Device, and Mobileuser are hibernate generated objects. the process works until i get to the second "if" conditional where I call mobileUser.getPin(). The problem is that mobileUser's properties (such as pin) are null. The values exist in the DB, but they area null, so my calls throw null pointer exceptions. Mobileuser's properties haven't been hydrated by hibernate. Any help is appreciated. Thanks.
DeviceDAO deviceDao = new DeviceDAO();
List<Device> devices = deviceDao.findByUdid(requestTokenModel.getUdid());
if(!devices.isEmpty())
{
Device device = devices.get(0);
Mobileuser mobileUser =device.getMobileuser();
if(mobileUser.getPin().contentEquals(requestTokenModel.getPiin()) && mobileUser.getIsactive() == "Y")
{
//omitted
}
}
UPDATE
Here's some more information as requested:
I am using MyEclipse Hibernate Reverse Engineering to generated data objects and DAO objects. Using annotations for mapping.
Here is Mobileuser.java
package com.myeclipse.hibernate;
import java.util.Date;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
/**
* Mobileuser entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "MOBILEUSER", schema = "WARPVALID")
public class Mobileuser implements java.io.Serializable {
// Fields
private Integer mobileuserid;
private Servicetype servicetype;
private String lastname;
private String username;
private String firstname;
private String organization;
private String piin;
private String isactive;
private Date createdate;
private Date modifydate;
private String email;
private String isaccepted;
private Set<Registration> registrations = new HashSet<Registration>(0);
private Set<Device> devices = new HashSet<Device>(0);
// Constructors
/** default constructor */
public Mobileuser() {
}
/** minimal constructor */
public Mobileuser(String lastname, String username, String firstname,
String piin, String isactive, Date createdate, Date modifydate,
String isaccepted) {
this.lastname = lastname;
this.username = username;
this.firstname = firstname;
this.piin = piin;
this.isactive = isactive;
this.createdate = createdate;
this.modifydate = modifydate;
this.isaccepted = isaccepted;
}
/** full constructor */
public Mobileuser(Servicetype servicetype, String lastname,
String username, String firstname, String organization,
String piin, String isactive, Date createdate, Date modifydate,
String email, String isaccepted, Set<Registration> registrations,
Set<Device> devices) {
this.servicetype = servicetype;
this.lastname = lastname;
this.username = username;
this.firstname = firstname;
this.organization = organization;
this.piin = piin;
this.isactive = isactive;
this.createdate = createdate;
this.modifydate = modifydate;
this.email = email;
this.isaccepted = isaccepted;
this.registrations = registrations;
this.devices = devices;
}
// Property accessors
#GenericGenerator(name = "generator", strategy = "increment")
#Id
#GeneratedValue(generator = "generator")
#Column(name = "MOBILEUSERID", unique = true, nullable = false, precision = 9, scale = 0)
public Integer getMobileuserid() {
return this.mobileuserid;
}
public void setMobileuserid(Integer mobileuserid) {
this.mobileuserid = mobileuserid;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "SERVICETYPEID")
public Servicetype getServicetype() {
return this.servicetype;
}
public void setServicetype(Servicetype servicetype) {
this.servicetype = servicetype;
}
#Column(name = "LASTNAME", nullable = false, length = 30)
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Column(name = "USERNAME", nullable = false, length = 20)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "FIRSTNAME", nullable = false, length = 30)
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(name = "ORGANIZATION", length = 50)
public String getOrganization() {
return this.organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
#Column(name = "PIIN", nullable = false, length = 10)
public String getPiin() {
return this.piin;
}
public void setPiin(String piin) {
this.piin = piin;
}
#Column(name = "ISACTIVE", nullable = false, length = 1)
public String getIsactive() {
return this.isactive;
}
public void setIsactive(String isactive) {
this.isactive = isactive;
}
#Temporal(TemporalType.DATE)
#Column(name = "CREATEDATE", nullable = false, length = 7)
public Date getCreatedate() {
return this.createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
#Temporal(TemporalType.DATE)
#Column(name = "MODIFYDATE", nullable = false, length = 7)
public Date getModifydate() {
return this.modifydate;
}
public void setModifydate(Date modifydate) {
this.modifydate = modifydate;
}
#Column(name = "EMAIL", length = 50)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "ISACCEPTED", nullable = false, length = 1)
public String getIsaccepted() {
return this.isaccepted;
}
public void setIsaccepted(String isaccepted) {
this.isaccepted = isaccepted;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "mobileuser")
public Set<Registration> getRegistrations() {
return this.registrations;
}
public void setRegistrations(Set<Registration> registrations) {
this.registrations = registrations;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "mobileuser")
public Set<Device> getDevices() {
return this.devices;
}
public void setDevices(Set<Device> devices) {
this.devices = devices;
}
}
And this is Device.java:
package com.myeclipse.hibernate;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* Device entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "DEVICE", schema = "WARPVALID")
public class Device implements java.io.Serializable {
// Fields
private Integer deviceid;
private Mobileuser mobileuser;
private String udid;
private String applicationversion;
private String dataversion;
private Set<Authentication> authentications = new HashSet<Authentication>(0);
// Constructors
/** default constructor */
public Device() {
}
/** minimal constructor */
public Device(Mobileuser mobileuser, String udid) {
this.mobileuser = mobileuser;
this.udid = udid;
}
/** full constructor */
public Device(Mobileuser mobileuser, String udid,
String applicationversion, String dataversion,
Set<Authentication> authentications) {
this.mobileuser = mobileuser;
this.udid = udid;
this.applicationversion = applicationversion;
this.dataversion = dataversion;
this.authentications = authentications;
}
// Property accessors
#GenericGenerator(name = "generator", strategy = "increment")
#Id
#GeneratedValue(generator = "generator")
#Column(name = "DEVICEID", unique = true, nullable = false, precision = 9, scale = 0)
public Integer getDeviceid() {
return this.deviceid;
}
public void setDeviceid(Integer deviceid) {
this.deviceid = deviceid;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "MOBILEUSERID", nullable = false)
public Mobileuser getMobileuser() {
return this.mobileuser;
}
public void setMobileuser(Mobileuser mobileuser) {
this.mobileuser = mobileuser;
}
#Column(name = "UDID", nullable = false, length = 20)
public String getUdid() {
return this.udid;
}
public void setUdid(String udid) {
this.udid = udid;
}
#Column(name = "APPLICATIONVERSION", length = 20)
public String getApplicationversion() {
return this.applicationversion;
}
public void setApplicationversion(String applicationversion) {
this.applicationversion = applicationversion;
}
#Column(name = "DATAVERSION", length = 20)
public String getDataversion() {
return this.dataversion;
}
public void setDataversion(String dataversion) {
this.dataversion = dataversion;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "device")
public Set<Authentication> getAuthentications() {
return this.authentications;
}
public void setAuthentications(Set<Authentication> authentications) {
this.authentications = authentications;
}
}

Mobileuser.hbm has a property named "piin" while your Mobileuser class has a method getPin(). Is it possible that one of these is a typo? They should match, assuming that they are meant to represent the same information. As should the setter, setPin(String) or setPiin(String) whichever it should be.
If the db has a column "piin", you can change the mapping to map property pin to column piin, though this means you won't be able to regenerate the mapping from the db in the future.

Scares me when this happens, but I just got back from lunch and now it's working correctly. Didn't make any changes from before, but it's happy now. No idea what was causing it.
Thanks for the debugging help #Corey.

Related

Deserialize Exception in spring hibernate with OneToOne Mapping

I am using Spring boot 2.1.2 with hibernate , and i have simple two model classes like user and user account, and these 2 models are connected with oneToOne mapping. When we call user, i need to get user account also. I just mapped user account model to user model with oneToOne mapping. But when i call user am facing one Deserialize Exception.
User model
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "tbl_user")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_account_id")
UserAccount userAccount;
#Column(name = "first_name",nullable = false)
private String firstName;
#Column(name = "active",nullable = false)
private Integer active;
#Column(name = "created_date",nullable = false)
private Calendar createdDate;
#Column(name = "created_by",nullable = false)
private Integer created_by;
#Column(name = "updated_date")
private Calendar updatedDate;
#Column(name = "updated_by")
private Integer updated_by;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer id, UserAccount userAccount, String firstName, Integer active, Calendar createdDate,
Integer created_by, Calendar updatedDate, Integer updated_by) {
super();
this.id = id;
this.userAccount = userAccount;
this.firstName = firstName;
this.active = active;
this.createdDate = createdDate;
this.created_by = created_by;
this.updatedDate = updatedDate;
this.updated_by = updated_by;
}
public Integer getId() {
return id;
}
public UserAccount getUserAccount() {
return userAccount;
}
public void setUserAccount(UserAccount userAccount) {
this.userAccount = userAccount;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Integer getCreated_by() {
return created_by;
}
public void setCreated_by(Integer created_by) {
this.created_by = created_by;
}
public Calendar getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Calendar updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getUpdated_by() {
return updated_by;
}
public void setUpdated_by(Integer updated_by) {
this.updated_by = updated_by;
}
}
UserAccount Model
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "tbl_user_account")
public class UserAccount implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "usere_name",nullable = false)
UserAccount usereName;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "active",nullable = false)
private Integer active;
#Column(name = "created_date",nullable = false)
private Calendar createdDate;
#Column(name = "created_by",nullable = false)
private Integer created_by;
#Column(name = "updated_date")
private Calendar updatedDate;
#Column(name = "updated_by")
private Integer updated_by;
public UserAccount(Integer id, UserAccount usereName, String password,Integer active,
Calendar createdDate, Integer created_by, Calendar updatedDate, Integer updated_by) {
super();
this.id = id;
this.usereName = usereName;
this.password = password;
this.active = active;
this.createdDate = createdDate;
this.created_by = created_by;
this.updatedDate = updatedDate;
this.updated_by = updated_by;
}
public UserAccount() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public UserAccount getUsereName() {
return usereName;
}
public void setUsereName(UserAccount usereName) {
this.usereName = usereName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Integer getCreated_by() {
return created_by;
}
public void setCreated_by(Integer created_by) {
this.created_by = created_by;
}
public Calendar getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Calendar updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getUpdated_by() {
return updated_by;
}
public void setUpdated_by(Integer updated_by) {
this.updated_by = updated_by;
}
}
Property file
# Application running port
server.port=8000
# Application running port
server.servlet.contextPath=/app
# Log files
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
#DB config
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
The problem seems to be in UserAccount class, where you defined usereName field as UserAccount type.
I think it should be a String.

Content type 'application/json;charset=UTF-8' not supported

I am creating a newsletter API using java spring framework. Whenever I am hitting the API as a post with request model getting this excetion org.springframework.web.HttpMediaTypeNotSupportedException.
This is my newsletter model
#Entity
#Table(name = "ns_newsletters")
public class Newsletter extends DomainObject {
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator = "newsletter_gen")
#TableGenerator(name = "newsletter_gen", table = "ns_newsletter_id_gen", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", pkColumnValue = "NewsletterId_Gen", initialValue = 1, allocationSize = 1)
#Column(name = "subscriber_id")
private int subscriberId;
#Column(name = "subscriber_email_address")
private String subscriberEmailAddress;
#Column(name = "is_subscribe")
public boolean isSubscribe;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "gender")
private String gender;
#JsonManagedReference
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "ns_newsletter_mailer_list_linkage", joinColumns = {#JoinColumn(name = "subscriber_id")},
inverseJoinColumns = {#JoinColumn(name = "newsletter_mailer_id")})
private Set<NewsletterMailerList> mailerLists;
public Newsletter() {
super();
}
public Newsletter(String createdBy, Timestamp creationDate, int version, Timestamp lastModifiedDate,
String lastModifiedBy, RecordStatus recordStatus) {
super(createdBy, creationDate, version, lastModifiedDate, lastModifiedBy, recordStatus);
}
public Newsletter(Set<NewsletterMailerList> mailerLists, int subscriberId, String subscriberEmailId, boolean isSubscribe, String firstName, String lastName, String sex) {
super();
this.subscriberId = subscriberId;
this.subscriberEmailAddress = subscriberEmailId;
this.isSubscribe = isSubscribe;
this.firstName = firstName;
this.lastName = lastName;
this.gender = sex;
this.mailerLists = mailerLists;
}
public int getSubscriberId() {
return subscriberId;
}
public void setSubscriberId(int subscriberId) {
this.subscriberId = subscriberId;
}
public String getSubscriberEmailAddress() {
return subscriberEmailAddress;
}
public void setSubscriberEmailAddress(String subscriberEmailAddress) {
this.subscriberEmailAddress = subscriberEmailAddress;
}
public boolean isSubscribe() {
return isSubscribe;
}
public void setSubscribe(boolean subscribe) {
isSubscribe = subscribe;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Set<NewsletterMailerList> getMailerLists() {
return mailerLists;
}
public void setMailerLists(Set<NewsletterMailerList> mailerLists) {
this.mailerLists = mailerLists;
}
}
This is my NewsletterMailerList model
#Entity
#Table(name = "ns_newsletter_mailer_list")
public class NewsletterMailerList extends DomainObject {
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator = "newsletter_mailer_list_gen")
#TableGenerator(name = "newsletter_mailer_list_gen", table = "ns_newsletter_mailer_list_id_gen", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", pkColumnValue = "NewsletterMailerList_Gen", initialValue = 1000, allocationSize = 1)
#Column(name = "newsletter_mailer_id")
private int newsletterMailerId;
#Column(name = "mailer_list_name")
private String mailerListName;
#Column(name = "description")
private String description;
#JsonBackReference
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "mailerLists")
private Set<Newsletter> newsletters;
public Set<Newsletter> getNewsletter() {
return newsletters;
}
public void setNewsletter(Set<Newsletter> newsletters) {
this.newsletters = newsletters;
}
public int getNewsletterMailerId() {
return newsletterMailerId;
}
public void setNewsletterMailerId(int newsletterMailerId) {
this.newsletterMailerId = newsletterMailerId;
}
public String getMailerListName() {
return mailerListName;
}
public void setMailerListName(String mailerListName) {
this.mailerListName = mailerListName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Newsletter> getNewsletters() {
return newsletters;
}
public void setNewsletters(Set<Newsletter> newsletters) {
this.newsletters = newsletters;
}
}
I give contain type as application/json.
I am new to do this kind of stuff. Please help me why I am getting this error. If you need anything more let me know.
This is Newsletter Controller
package com.neostencil.modules.newslettermanagement.controller;
import com.neostencil.framework.base.BaseResponse;
import com.neostencil.framework.enums.StatusType;
import com.neostencil.framework.utilities.common.CollectionUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
#RestController
#RequestMapping(value = "api/v1")
#Api(value = "Newsletter", description = "Rest API for Newsletter
operations", tags = "Newsletter API")
public class NewsletterController {
#Autowired
NewsletterService newsletterService;
#RequestMapping(value = "/newsletters", method = RequestMethod.POST)
public ResponseEntity<BaseResponse> addNewsletter(RequestEntity<SingleNewsletterRequest> request) {
ResponseEntity<BaseResponse> response = null;
BaseResponse baseResponse = new BaseResponse();
List<String> messages = new ArrayList<>();
if (request.getBody() == null) {
baseResponse.setStatus(StatusType.NOT_FOUND);
messages.add("Newsletter request is empty or null");
baseResponse.setMessages(messages);
response = new ResponseEntity<BaseResponse>(baseResponse, HttpStatus.BAD_REQUEST);
} else {
Newsletter newsletter = request.getBody().getNewsletter();
Set<NewsletterMailerList> mailerLists = request.getBody().getNewsletter().getMailerLists();
if (CollectionUtil.isEmpty(mailerLists) || !mailerLists.contains(MailerListType.list_1) || !mailerLists.contains(MailerListType.list_2)) {
NewsletterMailerList newsletterMailerList1 = new NewsletterMailerList();
newsletterMailerList1.setMailerListName(MailerListType.list_1);
NewsletterMailerList newsletterMailerList2 = new NewsletterMailerList();
newsletterMailerList2.setMailerListName(MailerListType.list_2);
mailerLists.add(newsletterMailerList1);
mailerLists.add(newsletterMailerList2);
newsletter.setMailerLists(mailerLists);
}
newsletterService.addNewsletter(newsletter);
baseResponse.setStatus(StatusType.SUCCESSFUL);
messages.add("Newsletter added successfully");
baseResponse.setMessages(messages);
response = new ResponseEntity<BaseResponse>(baseResponse, HttpStatus.OK);
}
return response;
}
}
This is request class
public class SingleNewsletterRequest {
Newsletter newsletter;
public Newsletter getNewsletter() {
return newsletter;
}
public void setNewsletter(Newsletter newsletter) {
this.newsletter = newsletter;
}
}
In my case the issue occurred due to some functional methods of the DTO have the names that follow Java Beans naming conventions, e.g. isValid().
It was absent in a request json-representation and then, when it's deserialized in back-end side the issue occurred.
So, try to check if any Java Beans methods (get*, set*, is*) has no their counterparts in respective front-end objects and avoid such methods (I've just changed the name to simply valid()).
Hopefully this helps.
In your POST method add the consumes attribute
#RequestMapping(value = "/newsletters", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseResponse> addNewsletter(RequestEntity<SingleNewsletterRequest> request) {
....
}
this will assumes that the HTTP request you are creating actually has
Content-Type:application/json instead of text/plain
Answered here: https://stackoverflow.com/a/50567626/8956733
Try to remove #JsonManagedReference
A bit weird, but it did help me as well (see my comment below).

org.hibernate.QueryException: duplicate association path for #ManyToOne Criteria

I have two classes which has a relationship between them. These are
com.edfx.adb.persist.Activity:
package com.edfx.adb.persist.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.NaturalId;
#javax.persistence.Entity
#Table(name = "ACTIVITY")
public class Activity extends Entity {
#Transient
private static final long serialVersionUID = 4741665931936809028L;
private String activityId;
private String activityName;
private String activityDescription;
private Customer customer;
private ActivityType activityType;
private boolean active;
private Double mandays;
private Double price;
private String manager;
private List<Participation> participations;
public Activity() {
super();
}
#NaturalId
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
#Lob
#Column(name = "ACTIVITY_NAME", nullable = false)
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
#Lob
#Column(name = "ACTIVITY_DESCRIPTION", nullable = false)
public String getActivityDescription() {
return activityDescription;
}
public void setActivityDescription(String activityDescription) {
this.activityDescription = activityDescription;
}
#ManyToOne
#JoinColumn(name = "CUSTOMER_ID", nullable = false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#ManyToOne
#JoinColumn(name = "ACTIVITY_TYPE_ID", nullable = false)
public ActivityType getActivityType() {
return activityType;
}
public void setActivityType(ActivityType activityType) {
this.activityType = activityType;
}
#Column(name = "ACTIVE", nullable = false)
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "MANDAYS")
public Double getMandays() {
return mandays;
}
public void setMandays(Double mandays) {
this.mandays = mandays;
}
#Column(name = "PRICE")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Column(name = "CUSTOMER_SIDE_MANAGER")
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
#OneToMany(mappedBy = "activity", fetch = FetchType.LAZY)
#Cascade(CascadeType.SAVE_UPDATE)
public List<Participation> getParticipations() {
return participations;
}
public void setParticipations(List<Participation> participations) {
this.participations = participations;
}
}
com.edfx.adb.persist.ActivityType:
package com.edfx.adb.persist.entity;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Transient;
#javax.persistence.Entity
#Table(name = "ACTIVITY_TYPE")
public class ActivityType extends Entity {
#Transient
private static final long serialVersionUID = 2322745769010162801L;
private String parent;
private String name;
private String activityId;
public ActivityType() {
}
#Column(name = "PARENT", nullable = false)
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
}
Both of them extends com.edfx.adb.persist.entity.Entity:
package com.edfx.adb.persist.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.hibernate.proxy.HibernateProxyHelper;
#MappedSuperclass
public class Entity implements Serializable {
#Transient
private static final long serialVersionUID = 7470288121057059283L;
private Long id;
private Date createTimestamp;
private Date lastUpdateTimestamp;
private Long version;
public Entity() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", updatable = false, nullable = false, unique = true)
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATE_TIMESTAMP")
public Date getCreateTimestamp() {
return createTimestamp;
}
public void setCreateTimestamp(Date createTimestamp) {
this.createTimestamp = createTimestamp;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_UPDATE_TIMESTAMP")
public Date getLastUpdateTimestamp() {
return lastUpdateTimestamp;
}
public void setLastUpdateTimestamp(Date lastUpdateTimestamp) {
this.lastUpdateTimestamp = lastUpdateTimestamp;
}
#Version
#Column(name = "VERSION")
public Long getVersion() {
return version;
}
#SuppressWarnings("unused")
private void setVersion(Long version) {
this.version = version;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
return prime * result + ((getId() == null) ? super.hashCode() : getId().hashCode());
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().equals(HibernateProxyHelper.getClassWithoutInitializingProxy(obj))) {
return false;
}
final Entity other = (Entity) obj;
if (getId() != other.getId()) {
if (getId() == null) {
return false;
}
if (!getId().equals(other.getId())) {
return false;
}
}
return true;
}
}
Now I am using Primefaces datatable to show a List<Activity> in which I have filtering on the field name of ActivityType. ActivityType is associated with Activity by #ManyToOne relationship.
For filtering the List<Activity> I am using:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType").add(Restrictions.like("name", value.toString(), MatchMode.START));
I am getting:
null: org.hibernate.QueryException: duplicate association path: activityType
at org.hibernate.loader.criteria.CriteriaQueryTranslator.createAssociationPathCriteriaMap(CriteriaQueryTranslator.java:172) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaQueryTranslator.<init>(CriteriaQueryTranslator.java:111) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:84) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1602) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at com.edfx.adb.dao.ActivityDao.loadActivities(ActivityDao.java:54) [classes:]
at com.edfx.adb.service.ActivityService.loadActivities(ActivityService.java:101) [classes:]
This error is not showing always and never after the first load. After filtering the table for 5-6 time, I am having this error.
I am worried that if the mapping and the criteria is right or not. Any suggestion would be very helpful.
I think you need to provide an alias, so you should change your code this way:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType", "at")
.add(
Restrictions.like("at.name", value.toString(), MatchMode.START));

PropertyNotFoundException: Target Unreachable, 'null' returned null [duplicate]

This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
Hello i have new Problem with Add Form
my problem here
WARNING: /test.xhtml #24,173 value="#{userController.users.username}": Target Unreachable, 'null' returned null
javax.el.PropertyNotFoundException: /test.xhtml #24,173 value="#{userController.users.username}": Target Unreachable, 'null' returned null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:93)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:95)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1008)
at javax.faces.component.UIInput.validate(UIInput.java:934)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1189)
at javax.faces.component.UIInput.processValidators(UIInput.java:691)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIForm.processValidators(UIForm.java:243)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1180)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:619)
and my back bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ejb.controller;
import com.ejbbean.iUserBean;
import com.entity.Igroup;
import com.entity.Iuser;
import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
/**
*
* #author KencyWindy
*/
#ManagedBean
#ViewScoped
public class UserController implements Serializable{
#EJB
private iUserBean iUserBean;
private Iuser users ;
private Igroup groupa;
public UserController() {
}
public Igroup getGroupa() {
return groupa;
}
public void setGroupa(Igroup groupa) {
this.groupa = groupa;
}
public Iuser getUsers() {
return users;
}
public void setUsers(Iuser users) {
this.users = users;
}
public List<Iuser> getAllUser(){
return iUserBean.retrieve();
}
public void addUser(){
users = new Iuser();
users = iUserBean.createUser(users);
}
public javax.faces.model.SelectItem[] getAllOfGroups(){
SelectItem[] options = null;
List<Igroup> lgroup = iUserBean.retrieveGroup();
if(lgroup.size() > 0 && lgroup != null){
options = new SelectItem[lgroup.size()];
int i = 0 ;
for ( Igroup igroup : lgroup){
options[i++] = new SelectItem(igroup.getGId(), igroup.getGroupname());
}
}
return options;
}
public void submit(ActionEvent event) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Correct", "Correct");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Igroup Entity Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* #author KencyWindy
*/
#Entity
#Table(name = "igroup")
#NamedQueries({
#NamedQuery(name = "Igroup.findAll", query = "SELECT i FROM Igroup i"),
#NamedQuery(name = "Igroup.findByGId", query = "SELECT i FROM Igroup i WHERE i.gId = :gId"),
#NamedQuery(name = "Igroup.findByGroupname", query = "SELECT i FROM Igroup i WHERE i.Groupname = :Groupname"),
#NamedQuery(name = "Igroup.findByAdministrator", query = "SELECT i FROM Igroup i WHERE i.administrator = :administrator"),
#NamedQuery(name = "Igroup.findByReaded", query = "SELECT i FROM Igroup i WHERE i.readed = :readed"),
#NamedQuery(name = "Igroup.findByDeleted", query = "SELECT i FROM Igroup i WHERE i.deleted = :deleted"),
#NamedQuery(name = "Igroup.findByUpdated", query = "SELECT i FROM Igroup i WHERE i.updated = :updated"),
#NamedQuery(name = "Igroup.findByModed", query = "SELECT i FROM Igroup i WHERE i.moded = :moded"),
#NamedQuery(name = "Igroup.findByAdded", query = "SELECT i FROM Igroup i WHERE i.added = :added")})
public class Igroup implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "g_id")
private Integer gId;
#Basic(optional = false)
#Column(name = "g_name")
private String Groupname;
#Column(name = "administrator")
private Boolean administrator;
#Basic(optional = false)
#Column(name = "readed")
private boolean readed;
#Column(name = "deleted")
private Boolean deleted;
#Column(name = "updated")
private Boolean updated;
#Column(name = "moded")
private Boolean moded;
#Column(name = "added")
private Boolean added;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "igroup")
private List<Iuser> iuserList;
public Igroup() {
}
public Igroup(Integer gId) {
this.gId = gId;
}
public Igroup(Integer gId, String gName, boolean readed) {
this.gId = gId;
this.Groupname = gName;
this.readed = readed;
}
public Integer getGId() {
return gId;
}
public void setGId(Integer gId) {
this.gId = gId;
}
public String getGroupname() {
return Groupname;
}
public void setGroupname(String Groupname) {
this.Groupname = Groupname;
}
public Boolean getAdministrator() {
return administrator;
}
public void setAdministrator(Boolean administrator) {
this.administrator = administrator;
}
public boolean getReaded() {
return readed;
}
public void setReaded(boolean readed) {
this.readed = readed;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public Boolean getUpdated() {
return updated;
}
public void setUpdated(Boolean updated) {
this.updated = updated;
}
public Boolean getModed() {
return moded;
}
public void setModed(Boolean moded) {
this.moded = moded;
}
public Boolean getAdded() {
return added;
}
public void setAdded(Boolean added) {
this.added = added;
}
public List<Iuser> getIuserList() {
return iuserList;
}
public void setIuserList(List<Iuser> iuserList) {
this.iuserList = iuserList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (gId != null ? gId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Igroup)) {
return false;
}
Igroup other = (Igroup) object;
if ((this.gId == null && other.gId != null) || (this.gId != null && !this.gId.equals(other.gId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Igroup[gId=" + gId + "]";
}
}
Iuser Entity Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* #author KencyWindy
*/
#Entity
#Table(name = "iuser")
#NamedQueries({
#NamedQuery(name = "Iuser.findAll", query = "SELECT i FROM Iuser i"),
#NamedQuery(name = "Iuser.findByUid", query = "SELECT i FROM Iuser i WHERE i.uid = :uid"),
#NamedQuery(name = "Iuser.findByUsername", query = "SELECT i FROM Iuser i WHERE i.username = :username"),
#NamedQuery(name = "Iuser.findByPassword", query = "SELECT i FROM Iuser i WHERE i.password = :password"),
#NamedQuery(name = "Iuser.findByPnum", query = "SELECT i FROM Iuser i WHERE i.pnum = :pnum"),
#NamedQuery(name = "Iuser.findByZipcode", query = "SELECT i FROM Iuser i WHERE i.zipcode = :zipcode"),
#NamedQuery(name = "Iuser.findByState", query = "SELECT i FROM Iuser i WHERE i.state = :state"),
#NamedQuery(name = "Iuser.findByDob", query = "SELECT i FROM Iuser i WHERE i.dob = :dob"),
#NamedQuery(name = "Iuser.findByEmail", query = "SELECT i FROM Iuser i WHERE i.email = :email"),
#NamedQuery(name = "Iuser.findByLastlogin", query = "SELECT i FROM Iuser i WHERE i.lastlogin = :lastlogin"),
#NamedQuery(name = "Iuser.findByRegdate", query = "SELECT i FROM Iuser i WHERE i.regdate = :regdate"),
#NamedQuery(name = "Iuser.findByAddress", query = "SELECT i FROM Iuser i WHERE i.address = :address"),
#NamedQuery(name = "Iuser.findByCity", query = "SELECT i FROM Iuser i WHERE i.city = :city")})
public class Iuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "uid")
private Integer uid;
#Basic(optional = false)
#Column(name = "username")
private String username;
#Basic(optional = false)
#Column(name = "password")
private String password;
#Basic(optional = false)
#Column(name = "pnum")
private int pnum;
#Basic(optional = false)
#Column(name = "zipcode")
private int zipcode;
#Basic(optional = false)
#Column(name = "state")
private String state;
#Basic(optional = false)
#Column(name = "dob")
#Temporal(TemporalType.TIMESTAMP)
private Date dob;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Column(name = "lastlogin")
#Temporal(TemporalType.TIMESTAMP)
private Date lastlogin;
#Column(name = "regdate")
#Temporal(TemporalType.TIMESTAMP)
private Date regdate;
#Basic(optional = false)
#Column(name = "address")
private String address;
#Basic(optional = false)
#Column(name = "city")
private String city;
#JoinColumn(name = "igroup", referencedColumnName = "g_id")
#ManyToOne(optional = false)
private Igroup igroup;
public Iuser() {
}
public Iuser(Integer uid) {
this.uid = uid;
}
public Iuser(Integer uid, String username, String password, int pnum, int zipcode, String state, Date dob, String email, String address, String city) {
this.uid = uid;
this.username = username;
this.password = password;
this.pnum = pnum;
this.zipcode = zipcode;
this.state = state;
this.dob = dob;
this.email = email;
this.address = address;
this.city = city;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
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 int getPnum() {
return pnum;
}
public void setPnum(int pnum) {
this.pnum = pnum;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getLastlogin() {
return lastlogin;
}
public void setLastlogin(Date lastlogin) {
this.lastlogin = lastlogin;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Igroup getIgroup() {
return igroup;
}
public void setIgroup(Igroup igroup) {
this.igroup = igroup;
}
public Integer getGrouplist(){
return this.igroup.getGId();
}
public void setGrouplist(Integer intgroup){
this.igroup = new Igroup(intgroup);
}
#Override
public int hashCode() {
int hash = 0;
hash += (uid != null ? uid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Iuser)) {
return false;
}
Iuser other = (Iuser) object;
if ((this.uid == null && other.uid != null) || (this.uid != null && !this.uid.equals(other.uid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Iuser[uid=" + uid + "]";
}
}
value="#{userController.users.username}":
Target Unreachable, 'null' returned null
Either #{userController} or #{userController.users} is null.
My cents that #{userController.users} is null. You aren't prepopulating it in your bean. The #{userController} is correctly declared and used as #ManagedBean.
You need to prepopulate it in the postconstruct of the bean:
#PostConstruct
public void init() {
users = new Iuser();
}
In UserController class, declare your variable like this.
public Iuser users = new Iuser();
Because unless you use new Iuser() the object is not created and it will returned a null value.
initialize your Iuser class in backing bean like this way
public Iuser getUsers() {
if(users == null){
users = (Iuser )super.getInstance(Iuser.Class);
}
return users;
}
this will create a new Iuser object if the object become null

JPA/Hibernate persist does not appear to work

I'm using JPA (Hibernate implementation) to save objects to the database. Selecting works fine, but for some reason, saving doesn't work. I don't get any errors, but the database doesn't get changed either. This goes for both new entities and existing ones.
EPayment pay = new EPayment();
pay.setAmount(payment.getAmount());
...
pay.setUserByToUserId(receiver);
CompayDAO.get().save(pay);
CompayDAO.save()
public void save(Object ent) {
System.out.println("Persisting: " + ent + " using " + this);
this.em.persist(ent);
}
Console output:
Opening DOA nl.compay.entities.CompayDAO#b124fa
Persisting: nl.compay.entities.EUser#1e2fe5d using nl.compay.entities.CompayDAO#b124fa
Persisting: nl.compay.entities.EUser#30b601 using nl.compay.entities.CompayDAO#b124fa
Persisting: nl.compay.entities.EPayment#ed3b53 using nl.compay.entities.CompayDAO#b124fa
Closing DOA nl.compay.entities.CompayDAO#b124fa
EPayment
package nl.compay.entities;
// Generated 21-mei-2009 12:27:07 by Hibernate Tools 3.2.2.GA
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Payment generated by hbm2java
*/
#Entity
#Table(name = "payment", catalog = "compay")
public class EPayment implements java.io.Serializable {
private static final long serialVersionUID = -2578493336948256566L;
private Integer id;
private EUser userByToUserId;
private EUser userByFromUserId;
private String description;
private float amount;
private String method;
private Date paydate;
public EPayment() {
}
public EPayment(EUser userByToUserId, EUser userByFromUserId, float amount,
Date paydate) {
this.userByToUserId = userByToUserId;
this.userByFromUserId = userByFromUserId;
this.amount = amount;
this.paydate = paydate;
}
public EPayment(EUser userByToUserId, EUser userByFromUserId,
String description, float amount, String method, Date paydate) {
this.userByToUserId = userByToUserId;
this.userByFromUserId = userByFromUserId;
this.description = description;
this.amount = amount;
this.method = method;
this.paydate = paydate;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "to_user_id", nullable = false)
public EUser getUserByToUserId() {
return this.userByToUserId;
}
public void setUserByToUserId(EUser userByToUserId) {
this.userByToUserId = userByToUserId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "from_user_id", nullable = false)
public EUser getUserByFromUserId() {
return this.userByFromUserId;
}
public void setUserByFromUserId(EUser userByFromUserId) {
this.userByFromUserId = userByFromUserId;
}
#Column(name = "description", length = 1024)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "amount", nullable = false, precision = 8)
public float getAmount() {
return this.amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
#Column(name = "method", length = 50)
public String getMethod() {
return this.method;
}
public void setMethod(String method) {
this.method = method;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "paydate", nullable = false, length = 0)
public Date getPaydate() {
return this.paydate;
}
public void setPaydate(Date paydate) {
this.paydate = paydate;
}
}
As Sherkaner mentioned, a save doesn't result in an INSERT or UPDATE directly. You have to flush the session or - better in my opinion - close the unit of work / commit the transaction. You do have transactions?
use #Transactional on your method.....
#Transactional
public void save(Object ent){
.....
.....
}
The program doesn't have to sync with the database right away, have you tried this.em.flush(); somewhere?
Don't think this as bug in Hibernate implementation.This is desired behavior,you would like to have minimum communication with database so Hibernate(or any good ORM framework) will consolidate all your changes and will flush your changes in one go.

Categories