Not able to set location model to null in contact entity - java

I am working on a spring mvc app in which I have 2 model classes. Following are my model classes:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#ManyToOne
#JoinColumn(name="locationid")
private LocationModel locationModel;
public LocationModel getLocationModel() {
return locationModel;
}
public void setLocationModel(LocationModel locationModel) {
this.locationModel = locationModel;
}
public int getContactId() {
return contactId;
}
public void setContactId(int contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
and LocationModel
import java.util.List;
//import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Cascade;
#Entity
#Table(name="Location")
public class LocationModel {
#Id
#Column(name="locationid")
#GeneratedValue
private int locationId;
#Column(name="locationname")
private String locationName;
#Column(name="locationdesc")
private String locationDescription;
#Column(name="type")
private String locationType;
#Column(name="address")
private String address;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="district")
private String district;
#Column(name="lattitude")
private String lattitude;
#Column(name="longitude")
private String longitude;
#OneToMany(mappedBy = "locationModel")
private List<ContactModel> contactList;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLocationType() {
return locationType;
}
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 getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
public int getLocationId() {
return locationId;
}
public void setLocationId(int locationId) {
this.locationId = locationId;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getLocationDescription() {
return locationDescription;
}
public void setLocationDescription(String locationDescription) {
this.locationDescription = locationDescription;
}
}
On deleting location I want to set location of corresponding contacts to null. I am using following code for this:
public void selLocationToNull(int locationId) throws Exception {
try {
logger.info("deleteContact() begins:");
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel=:locationId");
query.setParameter("newLocation", null);
query.setParameter("locationId", locationId);
query.executeUpdate();
logger.info("null update query executed...");
} catch (Exception e) {
logger.debug("Error while updating location to null: "
+ e.getMessage());
throw e;
} finally {
}
}
I am getting exception for this:
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.bizmerlin.scm.model.LocationModel.locationId
Caused by: java.lang.IllegalArgumentException: Can not set int field com.bizmerlin.scm.model.LocationModel.locationId to java.lang.Integer
I have getter method for locationId in my LocationModel class.

How can you set a null to a primitive type? It is generally good practice to use wrapper types for fields in your Entity.
#Id
#Column(name="locationid")
#GeneratedValue
private Integer locationId;

You set in the query's where LocationModel and compare it with int. SHould be
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel.id=:locationId");
instead. Or pass the LocationModel instance rather than id

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;

Join in hibernate with annotaion

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

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.

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 ?

Spring MVC Hibernate web application

Spring MVC + Hibernate web application with mysql database.
3 tables (products, members and cart to connect this two). Members table have two different users: admin and customer.
It should be something like Online Store.
To have Administrator and Customer users. Admin entering new, edit and delete products. Customer to list all products and add to cart part.
But before that it should have log in and sign up part. So Admin or Customer can log in or sign up.
So I have welcome page, index.jsp, from which I need links to:
all_products.jsp -> list all products from products table mysql database
signup.jsp -> Add new member form and sending data to members table mysql database.
login.jsp -> Log In form
From login.jsp depending who logged in:
Customer -> index.jsp
Admin -> admin.jsp
admin.jsp -> add.jsp, all_products.jsp with edit and delete option.
add.jsp-> add new product form
I setup up a new project in Netbeans, with Spring mvc and hibernate framework, connect with mysql database, set up server, glassfish... etc...
Then add...
Members.java
package model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name="members")
public class Members implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int memberId;
private String userName;
private String password;
private String fullName;
private String email;
private String address;
private String gender;
private String dateOfBirth;
private String memberType;
private Set<Cart> carts = new HashSet<Cart>(0);
public Members() {
}
public Members(int memberId) {
this.memberId = memberId;
}
public Members(int memberId, String userName, String password, String fullName, String email, String address, String gender, String dateOfBirth, String memberType, Set<Cart> carts) {
this.memberId = memberId;
this.userName = userName;
this.password = password;
this.fullName = fullName;
this.email = email;
this.address = address;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.memberType = memberType;
this.carts = carts;
}
public int getMemberId() {
return this.memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getMemberType() {
return this.memberType;
}
public void setMemberType(String memberType) {
this.memberType = memberType;
}
public Set<Cart> getCarts() {
return this.carts;
}
public void setCarts(Set<Cart> carts) {
this.carts = carts;
}
}
Products.java
package model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name="products")
public class Products implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int productId;
private String productName;
private String productType;
private String description;
private Double price;
private String productColor;
private String productBrand;
private String productSize;
private Integer allProductsQuantity;
private Set<Cart> carts = new HashSet<Cart>(0);
public Products() {
}
public Products(int productId) {
this.productId = productId;
}
public Products(int productId, String productName, String productType, String description, Double price, String productColor, String productBrand, String productSize, Integer allProductsQuantity, Set<Cart> carts) {
this.productId = productId;
this.productName = productName;
this.productType = productType;
this.description = description;
this.price = price;
this.productColor = productColor;
this.productBrand = productBrand;
this.productSize = productSize;
this.allProductsQuantity = allProductsQuantity;
this.carts = carts;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return this.productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return this.price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getProductColor() {
return this.productColor;
}
public void setProductColor(String productColor) {
this.productColor = productColor;
}
public String getProductBrand() {
return this.productBrand;
}
public void setProductBrand(String productBrand) {
this.productBrand = productBrand;
}
public String getProductSize() {
return this.productSize;
}
public void setProductSize(String productSize) {
this.productSize = productSize;
}
public Integer getAllProductsQuantity() {
return this.allProductsQuantity;
}
public void setAllProductsQuantity(Integer allProductsQuantity) {
this.allProductsQuantity = allProductsQuantity;
}
public Set<Cart> getCarts() {
return this.carts;
}
public void setCarts(Set<Cart> carts) {
this.carts = carts;
}
}
Cart.java
package model;
public class Cart implements java.io.Serializable {
private int cartId;
private Members members;
private Products products;
private Integer cartQuantity;
public Cart() {
}
public Cart(int cartId) {
this.cartId = cartId;
}
public Cart(int cartId, Members members, Products products, Integer cartQuantity) {
this.cartId = cartId;
this.members = members;
this.products = products;
this.cartQuantity = cartQuantity;
}
public int getCartId() {
return this.cartId;
}
public void setCartId(int cartId) {
this.cartId = cartId;
}
public Members getMembers() {
return this.members;
}
public void setMembers(Members members) {
this.members = members;
}
public Products getProducts() {
return this.products;
}
public void setProducts(Products products) {
this.products = products;
}
public Integer getCartQuantity() {
return this.cartQuantity;
}
public void setCartQuantity(Integer cartQuantity) {
this.cartQuantity = cartQuantity;
}
}
I add service also for this classes.
MemberService
package service;
import java.util.List;
import model.Members;
public interface MembersService {
public void add(Members members);
public void edit(Members members);
public void delete(int memberId);
public Members getMembers(int memverId);
public List getAllMembers();
}
ProductsService
package service;
import java.util.List;
import model.Products;
public interface ProductsService {
public void add(Products products);
public void edit(Products products);
public void delete(int productId);
public Products getProducts(int productId);
public List getAllProducts();
}
Also add ServiceImpl
MembersServiceImpl
package service;
import DAO.MembersDAO;
import java.util.List;
import javax.jms.Session;
import javax.transaction.Transactional;
import model.Members;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Service
public class MembersServiceImpl implements MembersService{
#Autowired
private MembersDAO membersDAO;
#Transactional
public void add(Members members) {
membersDAO.add(members);
}
#Transactional
public void edit(Members members) {
membersDAO.edit(members);
}
#Transactional
public void delete(int productId) {
membersDAO.delete(productId);
}
#Transactional
public Members getMembers(int productId) {
return membersDAO.getMembers(productId);
}
#Transactional
public List getAllMembers() {
return membersDAO.getAllMembers();
}
}
ProductsServiceImpl
package service;
import DAO.ProductsDAO;
import java.util.List;
import javax.jms.Session;
import javax.transaction.Transactional;
import model.Products;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Service
public class ProductsServiceImpl implements ProductsService{
#Autowired
private ProductsDAO productsDAO;
#Transactional
public void add(Products products) {
productsDAO.add(products);
}
#Transactional
public void edit(Products products) {
productsDAO.edit(products);
}
#Transactional
public void delete(int productId) {
productsDAO.delete(productId);
}
#Transactional
public Products getProducts(int productId) {
return productsDAO.getProducts(productId);
}
#Transactional
public List getAllProducts() {
return productsDAO.getAllProducts();
}
}
And ProductsContoller
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import service.ProductsService;
public class ProductsController extends SimpleFormController {
public ProductsController() {
setCommandClass(Products.class);
setCommandName("products");
setSuccessView("products");
setFormView("products");
}
protected ModelAndView products(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
Products products = (Products) command;
ModelAndView mv = new ModelAndView(getSuccessView());
/*ModelAndView addObject = mv.addObject("products", ProductsService.ProductsService(products.getValue()));*/
return mv;
}
#Autowired
private ProductsService productsService;
public void setProductsService(ProductsService productsService) {
this.productsService = productsService;
}
}
Here I am stack.
I also have simple MembersDAO.java, ProductsDAO.java and there implementations.
...and fist question is how to connect two .jsp pages?
How to make simple navigation bar to connect first all my .jsp(view) pages?
To make simple nav bar on header and use on all my pages.
I know i should use spring contorollers...
How to make simple controller that will take me to all_products.jsp from index.jsp and list all products from products table from mysql database???
How to import spring security, log in section in my app?
Also add new product form...
My app is working and deplopying...
I can upload web.xml and servlet.xml but did change things...
Can anyone help me?!
Thank you very much.
in your .jsp. create your navigation. If products on href doesn't work. Then add
${pageContext.request.contextPath}/products
this will be your navigation
<ul>
<li>
Home
</li>
<li>
Products
</li>
<li>
Users
</li>
</ul>
navigation should look like this or depends on what you want
Home
Products
Users
and the simple controller for the views or for your .jsp files.
#RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home() {
return new ModelAndView("home"); //home.jsp
}
#RequestMapping(value = "/products", method = RequestMethod.GET)
public ModelAndView products() {
return new ModelAndView("products");
}
#RequestMapping(value = "/users", method = RequestMethod.GET)
public ModelAndView users() {
return new ModelAndView("users");
}

Categories