Data not persisting in join column using spring-data - java

The hibernate output is as follows.
Hibernate: insert into usernew (ACTIVE, EMAIL, FIRST_NAME, CGUID, LAST_NAME, MIDDLE_NAME, PIN) values (?, ?, ?, ?, ?, ?, ?)
Hibernate:insert into usernew (ACTIVE, EMAIL, FIRST_NAME, CGUID, LAST_NAME,MIDDLE_NAME, PIN) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into eventnew (ACTIVE, ADDRESS, DESCRIPTION, END_TS, HOST_PHONE_NUMBER,IMAGE, LATITUDE, LONGITUDE, NAME, PLACE_ID, START_TS) values (?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?)
User user = new User();
user.setActive(true);
user.setFirstName("test");
user.setLastName("test");
user.setPin("3333");
user.setEmail("n#f.com");
userRepositoryNew.save(user);
User user1 = new User();
user1.setActive(true);
user1.setFirstName("test");
user1.setLastName("test");
user1.setPin("3333");
user1.setEmail("nauman#f1.com");
userRepositoryNew.save(user1);
Event event = new Event();
event.setName("event");
event.setDescription("testing event");
event.setHostPhoneNumber("4455-33-990");
event.setLongitude("dddd");
EventUser eventUser = new EventUser();
eventUser.setUser(user);
eventUser.setEvent(event);
EventUser eventUser1 = new EventUser();
eventUser.setUser(user1);
eventUser.setEvent(event);
event.getEventUsers().add(eventUser);
event.getEventUsers().add(eventUser1);
eventRepositoryNew.save(event);
Below is the code, not sure why join table is not getting populated.
package com.hive.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
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.Table;
import javax.persistence.Transient;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import com.hive.json.marshaller.DateUTCDeserializer;
import com.hive.json.marshaller.DateUTCSerializer;
import com.hive.json.marshaller.ImageDeserializer;
import com.hive.json.marshaller.ImageSerializer;
#Entity
#Table(name = "eventnew")
public class Event implements java.io.Serializable {
private Integer id;
private String name;
private String description;
private String address;
private String latitude;
private String longitude;
#JsonSerialize(using = ImageSerializer.class)
#JsonDeserialize(using = ImageDeserializer.class)
private byte[] image;
private String placeId;
#JsonSerialize(using = DateUTCSerializer.class)
#JsonDeserialize(using = DateUTCDeserializer.class)
private Date startAt;
#JsonSerialize(using = DateUTCSerializer.class)
#JsonDeserialize(using = DateUTCDeserializer.class)
private Date endAt;
private boolean active;
private String hostPhoneNumber;
private Set<User> participants = new HashSet<User>(0);
private Set<EventUser> eventUsers = new HashSet<EventUser>(0);
public Event() {
}
#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;
}
#Column(name = "NAME", nullable = false, length = 10)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "LATITUDE")
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
#Column(name = "LONGITUDE")
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
#Column(name = "START_TS")
public Date getStartAt() {
return startAt;
}
public void setStartAt(Date startAt) {
this.startAt = startAt;
}
#Column(name = "END_TS")
public Date getEndAt() {
return endAt;
}
public void setEndAt(Date endAt) {
this.endAt = endAt;
}
#Column(name = "IMAGE")
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Column(name = "PLACE_ID")
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
#Column(name = "ACTIVE")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "HOST_PHONE_NUMBER")
public String getHostPhoneNumber() {
return hostPhoneNumber;
}
public void setHostPhoneNumber(String hostPhoneNumber) {
this.hostPhoneNumber = hostPhoneNumber;
}
#Transient
public Set<User> getParticipants() {
return participants;
}
public void setParticipants(Set<User> participants) {
this.participants = participants;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.event")
public Set<EventUser> getEventUsers() {
return this.eventUsers;
}
public void setEventUsers(Set<EventUser> eventUsers) {
this.eventUsers = eventUsers;
}
}
package com.hive.domain;
import static javax.persistence.GenerationType.IDENTITY;
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.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "usernew")
public class User implements java.io.Serializable {
private String guid;
private String firstName;
private String middleName;
private String lastName;
private Integer phoneNumber;
private String email;
private String pin;
private boolean active;
private Set<EventUser> eventUsers = new HashSet<EventUser>(0);
public User() {
}
#Column(name = "CGUID")
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "PHONE_NUMBER", unique = true, nullable = false)
public Integer getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "MIDDLE_NAME")
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#Column(name = "EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "PIN")
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
#Column(name = "ACTIVE")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user", cascade = CascadeType.ALL)
public Set<EventUser> getEventUsers() {
return this.eventUsers;
}
public void setEventUsers(Set<EventUser> eventUsers) {
this.eventUsers = eventUsers;
}
}
package com.hive.domain;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name = "eventusernew", catalog = "hive")
#AssociationOverrides({ #AssociationOverride(name = "pk.user", joinColumns = #JoinColumn(name = "USER_ID") ),
#AssociationOverride(name = "pk.event", joinColumns = #JoinColumn(name = "EVENT_ID") ) })
public class EventUser implements java.io.Serializable {
private EventUserId pk = new EventUserId();
// private String state;
// private String comment;
// private String displayName;
public EventUser() {
}
// #Column(name = "STATE")
// public String getState() {
// return state;
// }
//
// #Column(name = "DISPLAY_NAME")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// #Column(name = "COMMENT")
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
#EmbeddedId
public EventUserId getPk() {
return pk;
}
public void setPk(EventUserId pk) {
this.pk = pk;
}
#Transient
public User getUser() {
return getPk().getUser();
}
public void setUser(User stock) {
getPk().setUser(stock);
}
#Transient
public Event getEvent() {
return getPk().getEvent();
}
public void setEvent(Event category) {
getPk().setEvent(category);
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
EventUser that = (EventUser) o;
if (getPk() != null ? !getPk().equals(that.getPk()) : that.getPk() != null)
return false;
return true;
}
public int hashCode() {
return (getPk() != null ? getPk().hashCode() : 0);
}
}
package com.hive.domain;
import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
#Embeddable
public class EventUserId implements java.io.Serializable {
private User user;
private Event event;
#ManyToOne
public User getUser() {
return user;
}
public void setUser(User stock) {
this.user = stock;
}
#ManyToOne
public Event getEvent() {
return event;
}
public void setEvent(Event category) {
this.event = category;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EventUserId that = (EventUserId) o;
if (user != null ? !user.equals(that.user) : that.user != null) return false;
if (event != null ? !event.equals(that.event) : that.event != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (user != null ? user.hashCode() : 0);
result = 31 * result + (event != null ? event.hashCode() : 0);
return result;
}
}

you need to cascade your save.
In your Event entity, change the one-to-many to something like this :
#OneToMany(mappedBy="pk.event", cascade=CascadeType.ALL)

Related

#AttributeOverride not working with Hibernate 5

I am using Hibernate version 5.2.6. I had an instance where I had to use #AttributeOverrides annotation to override the name of an embedded column attribute which I previously used with another entity. But it doesn't seem to be working.
I am getting
Hibernate ERROR - Unknown column 'ADDRESS_LINE_1' in 'field list
The following is my code:
Address.java
package com.myApps.data.entities;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
#Column(name="ADDRESS_LINE_1")
private String addressLine1;
#Column(name="ADDRESS_LINE_2")
private String addressLine2;
#Column(name="CITY")
private String city;
#Column(name="STATE")
private String state;
#Column(name="ZIP_CODE")
private String zipCode;
public Address() {
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
User.java
package com.myApps.data.entities;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Formula;
#Entity
#Table(name = "FINANCES_USER")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "BIRTH_DATE")
private Date birthDate;
#Column(name = "EMAIL_ADDRESS")
private String emailAddress;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="addressline1", column=#Column(name="USER_ADDRESS_LINE_1")),
#AttributeOverride(name="addressline2", column=#Column(name="USER_ADDRESS_LINE_2"))
})
private Address address;
#Column(name = "LAST_UPDATED_DATE")
private Date lastUpdatedDate;
#Column(name = "LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name = "CREATED_DATE", updatable = false)
private Date createdDate;
#Column(name = "CREATED_BY", updatable = false)
private String createdBy;
#Formula("lower(datediff(curdate(), birth_date)/365)")
private int age;
public int getAge() {
return age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void setAge(int age) {
this.age = age;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
}
Application.java
package com.myApps.data;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.myApps.data.entities.Address;
import com.myApps.data.entities.Bank;
import com.myApps.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
Transaction transaction = session.beginTransaction();
User user = new User();
Address address = new Address();
user.setFirstName("Beth");
user.setLastName("Crimson");
user.setCreatedBy("Mr Crimson");
user.setCreatedDate(new Date());
address.setAddressLine1("22nd street Meadows");
address.setAddressLine2("House no: 15");
user.setAddress(address);
session.save(user);
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
}
finally {
session.close();
}
}
}
I am getting
Hibernate ERROR - Unknown column 'ADDRESS_LINE_1' in 'field list'
I am not able to find any problem with my code.
Please help me resolve this.
If you use camelcase in #Embeddable:
#Column(name="ADDRESS_LINE_1")
private String addressLine1;
#Column(name="ADDRESS_LINE_2")
private String addressLine2;
Then you should use it in overrides as well:
#Embedded
#AttributeOverrides({
#AttributeOverride(name="addressLine1", column=#Column(name="USER_ADDRESS_LINE_1")),
#AttributeOverride(name="addressLine2", column=#Column(name="USER_ADDRESS_LINE_2"))
})
private Address address;

Mapped Entity null on #OneToOne with #JoinColumn

I get the mapped entity always null but, FetchType.EAGER is set already. I have a Booking entity class that maps to two other entities - Slot and Subscriber. Both the entities are null when I fetch the booking entity
Booking class
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#Entity
#Table(name = "BOOKING")
public class Booking {
public Booking(){
}
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "title")
private String title;
#Column(name = "descr")
private String desc;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "slotid",insertable = false, updatable = false)
private Slot slot;
private Integer slotid;
private Integer subscriberid;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "subscriberid",insertable = false, updatable = false)
private User subscriber;
#Column(name = "created")
#Temporal(TemporalType.TIMESTAMP)
private Date created;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "slotid",referencedColumnName="slotid")
public Slot getSlot() {
return slot;
}
public void setSlot(Slot slot) {
this.slot = slot;
}
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "subscriberid",referencedColumnName="userid")
public User getSubscriber() {
return subscriber;
}
public void setSubscriber(User subscriber) {
this.subscriber = subscriber;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Integer getSlotid() {
return slotid;
}
public void setSlotid(Integer slotid) {
this.slotid = slotid;
}
public Integer getSubscriberid() {
return subscriberid;
}
public void setSubscriberid(Integer subscriberid) {
this.subscriberid = subscriberid;
}
}
Slot class
import java.util.Date;
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;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#Entity
#Table(name="SLOT")
public class Slot {
public Slot(){
}
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="slotid")
private Integer id;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="ownerid",insertable = false, updatable = false)
private User user;
#Column(name="startdate")
private Date startdate;
#Column(name="enddate")
private Date enddate;
#Column(name="status")
private String status;
private Integer ownerid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false, updatable=false)
#Version
private Date created;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return this.user;
}
public void setUser(User owner) {
this.user = owner;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOwnerid() {
return ownerid;
}
public void setOwnerid(Integer ownerid) {
this.ownerid = ownerid;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
}
Subscriber - User class
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="users")
public class User {
public User(){
}
#Id#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="userid")
private Integer userid = 0;
#Column(name = "name")
private String name;
#Column(name = "mobile")
private String mobile;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "type")
private String userType;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="cityid",insertable = false, updatable = false)
private City city;
private String cityid;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="specialityid",insertable = false, updatable = false)
private Speciality speciality;
private Integer specialityid;
#Column(name="medregno")
private String regno;
#Column(name="refcode")
private String referalcode;
public String getRegno() {
return regno;
}
public void setRegno(String regno) {
this.regno = regno;
}
public String getReferalcode() {
return referalcode;
}
public void setReferalcode(String referalcode) {
this.referalcode = referalcode;
}
#Column(name = "gender")
private String gender;
#Column(name = "active")
private boolean active;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated")
private Date updated;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created")
private Date created;
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (userid != other.userid)
return false;
return true;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getCityid() {
return cityid;
}
public void setCityid(String cityid) {
this.cityid = cityid;
}
public Speciality getSpeciality() {
return speciality;
}
public void setSpeciality(Speciality speciality) {
this.speciality = speciality;
}
public Integer getSpecialityid() {
return specialityid;
}
public void setSpecialityid(Integer specialityid) {
this.specialityid = specialityid;
}
}
booking.getSlot() and booking.getSubscriber() returns null
Please let me know if i miss some configuration while mapping
EDIT1
Added code how the entity is getting loaded
public Booking addBooking(String title,String desc,int slotid,int subscriberid,Session session){
Booking booking = new Booking();
booking.setTitle(title);
booking.setDesc(desc);
booking.setSlotid(slotid);
booking.setSubscriberid(subscriberid);
booking.setCreated(new Date());
Integer bookingid = (Integer) session.save(booking);
session.flush();
Booking bookingEntity = (Booking) session.createQuery("From Booking where id = ?").
setParameter(0, bookingid).list().get(0);
return bookingEntity;
}
I am saving the entity and reloading it.
It's not working because Hibernate is retuning the same instance it has already in its 1st level cache, which doesn't have a reference to any of the 2 other entities.
To fix this, you have to do a session.refresh(booking) rather than executing a query.
In your code :
booking.setSlotid(slotid);
booking.setSubscriberid(subscriberid);
You're just setting Integer values and not objects. Instead of this, try to set objects :
booking.setSlot(new Slot(slotid));
booking.setSubscriber(new Subscriber(subscriberid));
But as #Augusto said, the associations you're having in the session (Slot and Subscriber) are not full objects they contain only their ids. That's why you can't get other fields of these objects.

How to display all reviews for a specific product using JSTL <c:forEach> tag?

I have set up a form that successfully insert a user product review into database. Now i'm trying to display all the reviews for the given product using c:forEach but it does not work. Basically im trying to tell the program for each selected product get productReviews but it returns blank. I have 3 classes (ProductReview, ProductHasReview, ProductHasReviewPK) that take care of holding the setter/getter methods as well as the session Beans for the entities.
Servlet
import entity.ProductHasReview;
import entity.Product;
import java.util.Collection;
import javax.ejb.EJB;
import session.ProductFacade;
#EJB
private ProductFacade productFacade;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
HttpSession session = request.getSession();
Collection<ProductHasReview> productReview = null;
// if product page is requested
} else if (userPath.equals("/viewProduct")) {
String productId = request.getQueryString();
if (productId != null) {
// get selected product
selectedProduct = productFacade.find(Integer.parseInt(productId));
// place selected product in session scope
session.setAttribute("selectedProduct", selectedProduct);
// get all reviews for selected products
productReview = selectedProduct.getProductHasReviewCollection();
// place products reviews in session scope
session.setAttribute("productReview", productReview);
}
userPath = "/product";
Product.jsp
<c:forEach var="product" items="${productReview}" varStatus="iter">
<div class="content ProdReviewRow">
<h3>${productReview.name}, ${productReview.age}, ${productReview.gender} </h3>
<h6>${productReview.dateCreated}<h6>
${productReview.review}
</div>
</c:forEach>
Product.java
package entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
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.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "product")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"),
#NamedQuery(name = "Product.findById", query = "SELECT p FROM Product p WHERE p.id = :id"),
#NamedQuery(name = "Product.findByPrice", query = "SELECT p FROM Product p WHERE p.price = :price"),
#NamedQuery(name = "Product.findByLastUpdate", query = "SELECT p FROM Product p WHERE p.lastUpdate = :lastUpdate")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 16777215)
#Column(name = "name")
private String name;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Basic(optional = false)
#NotNull
#Column(name = "price")
private BigDecimal price;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 2147483647)
#Column(name = "description")
private String description;
#Basic(optional = false)
#NotNull
#Column(name = "last_update")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdate;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 2147483647)
#Column(name = "faq")
private String faq;
#ManyToMany(mappedBy = "productCollection")
private Collection<Category> categoryCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<ProductHasBadRating> productHasBadRatingCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<OrderedProduct> orderedProductCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<ProductHasGoodRating> productHasGoodRatingCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<ProductHasReview> productHasReviewCollection;
public Product() {
}
public Product(Integer id) {
this.id = id;
}
public Product(Integer id, String name, BigDecimal price, String description, Date lastUpdate, String faq) {
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.lastUpdate = lastUpdate;
this.faq = faq;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public String getFaq() {
return faq;
}
public void setFaq(String faq) {
this.faq = faq;
}
#XmlTransient
public Collection<Category> getCategoryCollection() {
return categoryCollection;
}
public void setCategoryCollection(Collection<Category> categoryCollection) {
this.categoryCollection = categoryCollection;
}
#XmlTransient
public Collection<ProductHasBadRating> getProductHasBadRatingCollection() {
return productHasBadRatingCollection;
}
public void setProductHasBadRatingCollection(Collection<ProductHasBadRating> productHasBadRatingCollection) {
this.productHasBadRatingCollection = productHasBadRatingCollection;
}
#XmlTransient
public Collection<OrderedProduct> getOrderedProductCollection() {
return orderedProductCollection;
}
public void setOrderedProductCollection(Collection<OrderedProduct> orderedProductCollection) {
this.orderedProductCollection = orderedProductCollection;
}
#XmlTransient
public Collection<ProductHasGoodRating> getProductHasGoodRatingCollection() {
return productHasGoodRatingCollection;
}
public void setProductHasGoodRatingCollection(Collection<ProductHasGoodRating> productHasGoodRatingCollection) {
this.productHasGoodRatingCollection = productHasGoodRatingCollection;
}
#XmlTransient
public Collection<ProductHasReview> getProductHasReviewCollection() {
return productHasReviewCollection;
}
public void setProductHasReviewCollection(Collection<ProductHasReview> productHasReviewCollection) {
this.productHasReviewCollection = productHasReviewCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Product)) {
return false;
}
Product other = (Product) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Product[ id=" + id + " ]";
}
}
ProductReview.java
#Entity
#Table(name = "product_review")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "ProductReview.findAll", query = "SELECT p FROM ProductReview p"),
#NamedQuery(name = "ProductReview.findById", query = "SELECT p FROM ProductReview p WHERE p.id = :id"),
#NamedQuery(name = "ProductReview.findByName", query = "SELECT p FROM ProductReview p WHERE p.name = :name"),
#NamedQuery(name = "ProductReview.findByDateCreated", query = "SELECT p FROM ProductReview p WHERE p.dateCreated = :dateCreated"),
#NamedQuery(name = "ProductReview.findByCountry", query = "SELECT p FROM ProductReview p WHERE p.country = :country"),
#NamedQuery(name = "ProductReview.findByAge", query = "SELECT p FROM ProductReview p WHERE p.age = :age"),
#NamedQuery(name = "ProductReview.findByGender", query = "SELECT p FROM ProductReview p WHERE p.gender = :gender"),
#NamedQuery(name = "ProductReview.findByEmail", query = "SELECT p FROM ProductReview p WHERE p.email = :email")})
public class ProductReview implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Lob
#Size(max = 2147483647)
#Column(name = "review")
private String review;
#Size(max = 45)
#Column(name = "name")
private String name;
#Column(name = "date_created")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreated;
#Size(max = 45)
#Column(name = "country")
private String country;
#Size(max = 45)
#Column(name = "age")
private String age;
#Size(max = 45)
#Column(name = "gender")
private String gender;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 45)
#Column(name = "email")
private String email;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "productReview")
private Collection<ProductHasReview> productHasReviewCollection;
public ProductReview() {
}
public ProductReview(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlTransient
public Collection<ProductHasReview> getProductHasReviewCollection() {
return productHasReviewCollection;
}
public void setProductHasReviewCollection(Collection<ProductHasReview> productHasReviewCollection) {
this.productHasReviewCollection = productHasReviewCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 ProductReview)) {
return false;
}
ProductReview other = (ProductReview) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.ProductReview[ id=" + id + " ]";
}
}
ProductHasReview.java
package entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author PC
*/
#Entity
#Table(name = "product_has_review")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "ProductHasReview.findAll", query = "SELECT p FROM ProductHasReview p"),
#NamedQuery(name = "ProductHasReview.findByProductId", query = "SELECT p FROM ProductHasReview p WHERE p.productHasReviewPK.productId = :productId"),
#NamedQuery(name = "ProductHasReview.findByProductReviewId", query = "SELECT p FROM ProductHasReview p WHERE p.productHasReviewPK.productReviewId = :productReviewId"),
#NamedQuery(name = "ProductHasReview.findByQuantity", query = "SELECT p FROM ProductHasReview p WHERE p.quantity = :quantity")})
public class ProductHasReview implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected ProductHasReviewPK productHasReviewPK;
#Column(name = "quantity")
private Short quantity;
#JoinColumn(name = "product_id", referencedColumnName = "id", insertable = false, updatable = false)
#ManyToOne(optional = false)
private Product product;
#JoinColumn(name = "product_review_id", referencedColumnName = "id", insertable = false, updatable = false)
#ManyToOne(optional = false)
private ProductReview productReview;
public ProductHasReview() {
}
public ProductHasReview(ProductHasReviewPK productHasReviewPK) {
this.productHasReviewPK = productHasReviewPK;
}
public ProductHasReview(int productId, int productReviewId) {
this.productHasReviewPK = new ProductHasReviewPK(productId, productReviewId);
}
public ProductHasReviewPK getProductHasReviewPK() {
return productHasReviewPK;
}
public void setProductHasReviewPK(ProductHasReviewPK productHasReviewPK) {
this.productHasReviewPK = productHasReviewPK;
}
public Short getQuantity() {
return quantity;
}
public void setQuantity(Short quantity) {
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public ProductReview getProductReview() {
return productReview;
}
public void setProductReview(ProductReview productReview) {
this.productReview = productReview;
}
#Override
public int hashCode() {
int hash = 0;
hash += (productHasReviewPK != null ? productHasReviewPK.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 ProductHasReview)) {
return false;
}
ProductHasReview other = (ProductHasReview) object;
if ((this.productHasReviewPK == null && other.productHasReviewPK != null) || (this.productHasReviewPK != null && !this.productHasReviewPK.equals(other.productHasReviewPK))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.ProductHasReview[ productHasReviewPK=" + productHasReviewPK + " ]";
}
}

MappedBy in a OneToOne Mapping

I have created Three classes- User, UserSubscription and Subscription. I want that users in the UserSubscription table should be referenced by the users existing in the User table. So, how to use mappedBy?
The classes are as follows:
User:
package com.model;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
#Entity
public class User {
private int userId;
private String password;
private String contact;
private String firstName;
private String lastName;
private String gender;
private String address;
private int age;
private String email;
private String countBooks;
private Set<Language> languages = new HashSet<Language>(0);
private Set<Book> favorites = new HashSet<Book>(0);
#Id
#GeneratedValue
#Column(name="User_Id")
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#Column(name="Password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="Contact")
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
#Column(name="First_Name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="Last_Name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="Gender")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name="Address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name="Age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Column(name="Email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="Count_Books")
public String getCountBooks() {
return countBooks;
}
public void setCountBooks(String countBooks) {
this.countBooks = countBooks;
}
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="User_Language", joinColumns = {
#JoinColumn(name = "User_Id", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "Language_Id",
nullable = false, updatable = false) })
public Set<Language> getLanguages() {
return languages;
}
public void setLanguages(Set<Language> languages) {
this.languages = languages;
}
#ManyToMany
#JoinTable(name="User_Favorite", joinColumns = {
#JoinColumn(name = "User_Id", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "Book_Id",
nullable = false, updatable = false) })
public Set<Book> getFavorites() {
return favorites;
}
public void setFavorites(Set<Book> favorites) {
this.favorites = favorites;
}
}
UserSubscription:
package com.model;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
#Entity
public class UserSubscription {
private int userSubscriptionId;
private Subscription subscription;
private User user;
private Date subscriptionStartDate;
private Date subscriptionEndDate;
private int status;
#Id
#GeneratedValue
#Column(name="User_Subscription_Id")
public int getUserSubscriptionId() {
return userSubscriptionId;
}
public void setUserSubscriptionId(int userSubscriptionId) {
this.userSubscriptionId = userSubscriptionId;
}
#Column(name="Subscription_Id")
public Subscription getSubscription() {
return subscription;
}
public void setSubscription(Subscription subscription) {
this.subscription = subscription;
}
#OneToOne(mappedBy="userId")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name="Subscription_Start_Date")
public Date getSubscriptionStartDate() {
return subscriptionStartDate;
}
public void setSubscriptionStartDate(Date subscriptionStartDate) {
this.subscriptionStartDate = subscriptionStartDate;
}
#Column(name="Subscription_End_Date")
public Date getSubscriptionEndDate() {
return subscriptionEndDate;
}
public void setSubscriptionEndDate(Date subscriptionEndDate) {
this.subscriptionEndDate = subscriptionEndDate;
}
#Column(name="Status")
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
Subscription:
package com.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Subscription {
private int subscriptionId;
private String name;
private int period;
private float fees;
private int noOfBooks;
private int Status;
#Id
#GeneratedValue
public int getSubscriptionId() {
return subscriptionId;
}
public void setSubscriptionId(int subscriptionId) {
this.subscriptionId = subscriptionId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public float getFees() {
return fees;
}
public void setFees(float fees) {
this.fees = fees;
}
public int getNoOfBooks() {
return noOfBooks;
}
public void setNoOfBooks(int noOfBooks) {
this.noOfBooks = noOfBooks;
}
public int getStatus() {
return Status;
}
public void setStatus(int status) {
Status = status;
}
}
Exception while executing:
Exception in thread "main" org.hibernate.AnnotationException: Referenced property not a (One|Many)ToOne: com.model.User.userId in mappedBy of com.model.UserSubscription.user
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:248)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1695)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1424)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at com.impetus.model.Check.main(Check.java:92)
In your code, user-user_subscription looks uni-directional. 'mappedby' should be used in bi-directional relationship.
You can use following code in user entity to make it bi-directional with user_subscription.
private UserSubscription userSubscription;
#OneToOne
public User getUserSubscription() {
return userSubscription;
}
Or remove mappedby from user_subscription and make it unidirectional.
Seems you are unsure of what mappedBy is used for or means. Database relationships are one sided; one table will have a foreign key reference to the target table. In JPA, you might map this relationship as a OneToOne and specify the foreign key to use with the #JoinColumn annotation:
#OneToOne(mappedBy="userId")
#JoinColumn(name = "USER_ID")
public User getUser() {
return user;
}
The Join column definition is optional, and if not used JPA will default to using the attribute name with "_" and the target entity's ID name prepended, so "USER_ID" in this case anyway.
Back to the database, because target table is referenced by the source table, this forms another implicit relationship back (the target table's ID can be used to look up the other table's foreign key). In JPA, this can be mapped again as a OneToOne or a OneToMany depending on the cardinality. If it is a OneToOne, you specify that this relationship does not define the foreign key by marking it as mappedBy the other relationship:
#OneToOne(mappedBy="user")
public UserSubscription getUserSubscription() {
return userSubscription;
}
But it is more likely a User will have multiple userSubscriptions:
#OneToMany(mappedBy="user")
public Collection<UserSubscription> getUserSubscriptions () {
return userSubscription ;
}
In both cases, you use the mappedBy to signal that there is a 'user' attribute in the target entity that defines a relationship to this entity and controls the foreign key setting in the database.
You also need to change how your define the UserSubscription->Subscription relationship, as you have defined an #Column on what appears to be a relationship. It should probably be
#OneToOne
#JoinColumn(name="Subscription_Id")
public Subscription getSubscription() {
return subscription;
}
you should have UserSubscription memeber and corrosponding gettes and setters in your User class like below:
private Set<Company> userSubscriptions = new HashSet<Company>(0);
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
public Set<UserSubscription> getUserSubscriptions() {
return this.userSubscriptions ;
}
public void setUserSubscriptions(Set<UserSubscription> userSubscriptions ) {
this.userSubscriptions = userSubscriptions ;
}
and same way you should have user object as memeber in UserSubscription Entity class.
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
You are doing it wrong
class User {
UserSubscription userSubscription ;
#OneToOne
public UserSubscription getUserSubscription(){
return userSubscription ;
}
public void setUserSubscription(UserSubscription userSubscription ){
this.userSubscription = userSubscription ;
}
}
class UserSubscription {
#OneToOne(mappedBy="userSubscription")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

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

Categories