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.
Related
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.
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;
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)
I am trying to perform join in hibernate and i am using struts2.
I am working with hibernate using annotaions. Now i am unable to perform join between two tables.My first table is "studentprojects" which contain pid and email.Second table is "initialprojectdetials" which contains pid,name,description... similarly some other fields.I have to get the data of second table by performing join around pid of first table.
For this am using this query:
String hql="from InitialProjectDTO I join I.projectId S where I.projectId=:id";
Query query=session.createQuery(hql);
query.setParameter("id", id);
mail =query.list();
where mail is the arraylist of InitialProjectDTO.
And my InitialProjectDTO is:
package edu.pma.dto;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="initialprojectdetail")
public class InitialProjectDTO {
#Id
#Column(name="projectId")
#OneToMany(cascade=CascadeType.ALL)
#JoinTable(name="studentprojects",joinColumns=#JoinColumn(name="projectId"))
int projectId;
#Column(name="name")
String name;
#Column(name="description")
String description;
#Column(name="technology")
String technology;
#Column(name="guide")
String guide;
#Column(name="duration")
int duration;
#Column(name="status")
String status;
#Column(name="report")
String report;
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTechnology() {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
public String getGuide() {
return guide;
}
public void setGuide(String guide) {
this.guide = guide;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
my SudentProjectDTO is:
package edu.pma.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="studentprojects")
public class StudentProjectDTO {
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
#Id
#Column(name="email")
String email;
#Column(name="projectId")
int projectId;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
This is the error which i am getting:
Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: edu.pma.dto.InitialProjectDTO.projectId
Method "execute" failed for object edu.pma.actions.LoginAction#1096a56
File: org/hibernate/cfg/annotations/CollectionBinder.java
You should try to use different models
#Entity
public class InitialProjectDTO {
#OneToMany(mappedBy = "project")
private Collection<StudentProjectDTO> students;
}
#Entity
public class StudentProjectDTO {
#ManyToOne
private InitialProjectDTO project;
}
And with the proper model it shuld be easy to write hql, you might want to look here for examples https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html.
Also I would suggest to look here for example of models. http://viralpatel.net/blogs/hibernate-one-to-many-annotation-tutorial/
See following example might its help to you
#Entity
#Table(name="initialprojectdetail")
public class InitialProjectDTO {
private Integer initialProjectDTOId;
private Set<StudentProjectDTO > studentProjectDTO = new HashSet<StudentProjectDTO >(0);
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "initial_projectDTO_id", unique = true, nullable = false)
public Integer getInitialProjectDTOId() {
return this.initialProjectDTOId;
}
public void setInitialProjectDTOId(Integer initialProjectDTOId) {
this.initialProjectDTOId = initialProjectDTOId;
}
#OneToMany(mappedBy = "studentprojects", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
public Set<StudentProjectDTO> getUserRole() {
return this.studentProjectDTO;
}
public void setUserRole(Set<StudentProjectDTO> studentProjectDTO) {
this.studentProjectDTO = studentProjectDTO;
}
}
#Entity
#Table(name="studentprojects")
public class StudentProjectDTO {
private InitialProjectDTO project;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "initial_projectDTO_id", nullable = false)
public User getProject() {
return this.project;
}
public void setProject(InitialProjectDTO project) {
this.project = project;
}
}
your Query shoud be something like this
String hql="SELECT ip from InitialProjectDTO ip JOIN ip.studentProjectDTO sp WHERE sp.projectId = :id";
Query query=session.createQuery(hql);
query.setParameter("id", id);
mail =query.list();
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));