#AttributeOverride not working with Hibernate 5 - java

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;

Related

Deserialize Exception in spring hibernate with OneToOne Mapping

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

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.

javax.el.PropertyNotFoundException: Property 'EmailAddress' not found on type com.iid.users.model.UsersPrimary

I am new to spring,hibernate integration.
here are some code snippets and they are throwing javax.el.PropertyNotFoundException.
snippets are as follows
UsersPrimary.java
package com.iid.users.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name = "Users_Primary")
public class UsersPrimary implements Serializable {
#Id
#Column(name="Email_Address" ,unique=true , nullable=false ,length=30)
private String EmailAddress;
#Column(name="Password", nullable=false ,length=30)
private String Password;
#Column(name="First_Name", nullable=false ,length=30)
private String FirstName;
#Column(name="Last_Name", nullable=false ,length=30)
private String LastName;
#Column(name="Date_Of_Birth", nullable=false)
#DateTimeFormat(pattern="yyyy-MM-dd")
private Date DateOfBirth;
#Column(name="Sex", nullable=false ,length=30)
private String Sex;
#Column(name="RoleName", nullable=false ,length=30)
private String RoleName;
#Column(name="Creation_Time", insertable = false, updatable = false, columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp creationTime;
#Column(name="is_Enabled", nullable=false ,length=30)
private String isEnabled;
#Column(name="Enable_Time", insertable = false , columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Timestamp Enable_Time ;
public UsersPrimary() {
// TODO Auto-generated constructor stub
}
public UsersPrimary(String emailAddress, String password, String firstName, String lastName, Date dateOfBirth, String sex, String roleName, Timestamp creationTime, String isEnabled, Timestamp enable_Time) {
super();
EmailAddress = emailAddress;
Password = password;
FirstName = firstName;
LastName = lastName;
DateOfBirth = dateOfBirth;
Sex = sex;
RoleName = roleName;
this.creationTime = creationTime;
this.isEnabled = isEnabled;
Enable_Time = enable_Time;
}
public String getEmailAddress() {
return EmailAddress;
}
public void setEmailAddress(String emailAddress) {
EmailAddress = emailAddress;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public Date getDateOfBirth() {
return DateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
DateOfBirth = dateOfBirth;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getRoleName() {
return RoleName;
}
public void setRoleName(String roleName) {
RoleName = roleName;
}
public Timestamp getCreationTime() {
return creationTime;
}
public void setCreationTime(Timestamp creationTime) {
this.creationTime = creationTime;
}
public String getIsEnabled() {
return isEnabled;
}
public void setIsEnabled(String isEnabled) {
this.isEnabled = isEnabled;
}
public Timestamp getEnable_Time() {
return Enable_Time;
}
public void setEnable_Time(Timestamp enable_Time) {
Enable_Time = enable_Time;
}
}
below is snippet of controller method of controller class
SearchController.java
private UsersPrimaryService ups ;
#RequestMapping(value = "/search", method = RequestMethod.POST)
#ResponseBody
public ModelAndView search(#RequestParam(value="SearchField")String SearchField,HttpSession sessionObj, HttpServletRequest req) {
ModelAndView model = new ModelAndView();
System.out.println(SearchField);
sessionObj.setAttribute("searchResultList" , ups.searchUsersPrimaryList(SearchField));
model.setViewName("/WEB-INF/jsp/Search/searchResult");
return model;
}
and below is the snippet from the searchResult.jsp
<c:forEach items="${searchResultList}" var="UsersPrimary">
<c:out value="${UsersPrimary.EmailAddress}"></c:out> <c:out value="${UsersPrimary.FirstName}"></c:out> <c:out value="${UsersPrimary.LastName}"></c:out>
</c:forEach>
everytime i am running the code gettting
javax.el.PropertyNotFoundException: Property 'EmailAddress' not found on type com.iid.users.model.UsersPrimary
dont know why ? i am using spring 4.1.1 and hibernate 4.3.6. .
is that some kind of bug or my snippets are wrong ?
Is the getter for EmailAddress field called getEmailAddress()? It's probably an issue with upper/lower case field names. Generally, field names should start with lower case letter (so emailAddress instead of EmailAddress), it is a globally accepted convention and a lot of frameworks depend on it while using reflection.
While it may be a major refactoring for you, you should change your fields to be lowerCamelCase and in your particular case with the getter named getEmailAddress() it should work.
As a quick workaround, try changing the expression to <c:out value="${UsersPrimary.getEmailAddress()}"></c:out>.

Hibernate Automatically load relationships

I have the following Entity classes UserEntity and TicketEntity. A User has many tickets and many tickets can belong to a user. My question is, is there a way to automatically load all the tickets belonging to a pertaining user by using Hibernate or do I have to manually load all the entity relationships from the DB? I think the .load() does this but I'm not quite sure. In my case could I do something like
userEntity.load()
Any help is appreciated, thanks
UserEntity.java
package com.issuetracking.domain;
/**
*/
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="username")
private String username;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Transient
private String confirmpassword;
#Column(name="verified")
private boolean verified;
#Column(name="role_id")
private int role_id;
#OneToMany(fetch = FetchType.LAZY)
private List<TicketEntity> tickets;
//Getters/Setters
public List<TicketEntity> getTickets() {
return tickets;
}
public void setTickets(List<TicketEntity> tickets) {
this.tickets = tickets;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
TicketEntity.java
package com.issuetracking.domain;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="ticket")
public class TicketEntity {
#Id
#Column(name="ticket_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="date_created")
#Temporal( TemporalType.TIMESTAMP )
private Date date_created;
#Column(name="status_id")
private int status_id;
//private TicketStatus status;
#Column(name="urgency_id")
private int urgency_id;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity belongs_to;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity assigned_to;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getStatus_id() {
return status_id;
}
public void setStatus_id(int status_id) {
this.status_id = status_id;
}
public int getUrgency_id() {
return urgency_id;
}
public void setUrgency_id(int urgency_id) {
this.urgency_id = urgency_id;
}
public UserEntity getBelongs_to() {
return belongs_to;
}
public void setBelongs_to(UserEntity belongs_to) {
this.belongs_to = belongs_to;
}
public UserEntity getAssigned_to() {
return assigned_to;
}
public void setAssigned_to(UserEntity assigned_to) {
this.assigned_to = assigned_to;
}
}
A User has many tickets and many tickets can belong to a user.
In this case relationship should be ManyToMany
My question is, is there a way to automatically load all the tickets belonging to a pertaining user
Use EAGER FetchType instead of LAZY , Like
#OneToMany(fetch = FetchType.EAGER)
private List<TicketEntity> tickets;

Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)

I have spring application everytime I run and I try to login I got the following excpetion after login
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethod$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj:19)
at com.emc.fleet.domain.User.entityManager(User.java:1)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethodDispatch1$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj)
at com.emc.fleet.domain.User_Roo_Finder.ajc$interMethod$com_emc_fleet_domain_User_Roo_Finder$com_emc_fleet_domain_User$findUsersByUserIdEquals(User_Roo_Finder.aj:47)
at com.emc.fleet.domain.User.findUsersByUserIdEquals(User.java:1)
I have read many STO questions and checked all answers none of them succeded
this is my user class
package com.emc.fleet.domain
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
#RooJavaBean
#RooToString
#RooJpaActiveRecord(finders = { "findUsersByEmailLike", "findUsersByUserIdEquals", "findUsersByCostCenter", "findUsersByDepartmet" })
public class User {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#NotNull
private String firstName;
#NotEmpty
#NotNull
private String lastName;
#NotNull
private Long userId;
#Email
#NotNull
private String email;
#NotNull
private String address;
#NotNull
private String district;
private String deskPhone;
#NotEmpty
#NotNull
private String mobile;
#NotEmpty
#NotNull
private String password;
#Transient
private String retypePassword;
#OneToOne
private Department departmet;
#OneToOne
#JoinColumn(name = "cost_center")
private CostCenter costCenter;
private String managerName;
private boolean enabled = true;
#Enumerated(EnumType.STRING)
private Roles role = Roles.ROLE_USER;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getDeskPhone() {
return deskPhone;
}
public void setDeskPhone(String deskPhone) {
this.deskPhone = deskPhone;
}
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 getRetypePassword() {
return retypePassword;
}
public void setRetypePassword(String retypePassword) {
this.retypePassword = retypePassword;
}
public Department getDepartmet() {
return departmet;
}
public void setDepartmet(Department departmet) {
this.departmet = departmet;
}
public CostCenter getCostCenter() {
return costCenter;
}
public void setCostCenter(CostCenter costCenter) {
this.costCenter = costCenter;
}
public String getManagerName() {
return managerName;
}
public void setManagerName(String managerName) {
this.managerName = managerName;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Roles getRole() {
return role;
}
public void setRole(Roles role) {
this.role = role;
}
#Override
public String toString() {
return getEmail() + " - " + getUserId();
}
}
and this the user_Roo_Configurable file
package com.emc.fleet.domain;
import com.emc.fleet.domain.User;
import org.springframework.beans.factory.annotation.Configurable;
privileged aspect User_Roo_Configurable {
declare #type: User: #Configurable;
}
any clue ?

Categories