I am new in JPA
I created two entities Questionnaire and Patient
I want that Questionnaire will have data of Patient.
Before I created the Questionnaire with only patientId but now I want to add new structure to get all the patientData.
I added new field of patientData and added new join( I hope I did it ok ).
The problem when I call to query AllQuestionnaires I didn't get data of patientData.
Could you please advise me ?
#Entity
#NamedQueries({
#NamedQuery(name = "AllQuestionnaires", query = "select q from Questionnaire q order by q.patientId") })
public class Questionnaire implements Serializable {
private static final long serialVersionUID = 1L;
public Questionnaire() {
}
#Id
#GeneratedValue
private long id;
private long patientId;
private Timestamp created;
#OneToOne
#JoinColumn(name = "patientId" ,referencedColumnName = "id" , insertable = false, updatable = false)
private Patient patientData;
public Patient getPatient() {
return patientData;
}
public void setPatient(Patient patient) {
this.patientData = patient;
}
#OneToMany(cascade = CascadeType.ALL)
private List<QuestionnaireAnswer> answers;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getPatientId() {
return patientId;
}
public void setPatientId(long patientId) {
this.patientId = patientId;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public void setCreated(long created) {
this.created = new Timestamp(created);
}
public List<QuestionnaireAnswer> getAnswers() {
return answers;
}
public void setAnswers(List<QuestionnaireAnswer> answers) {
this.answers = answers;
}
}
class Patient
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Transient;
#Entity
#NamedQueries({
#NamedQuery(name = "AllPatients", query = "select p from Patient p"),
#NamedQuery(name = "PatientsByUserType", query = "select p from Patient p where p.userType = :userType"),
#NamedQuery(name = "PatientByEmail", query = "select p from Patient p where p.email = :email"),
#NamedQuery(name = "PatientById", query = "select p from Patient p where p.id = :id") })
public class Patient implements Serializable {
public enum UserType {
PATIENT,
CONTROL
}
private static final long serialVersionUID = 1L;
public Patient() {
}
#Id
#GeneratedValue
private long id;
private String firstName;
private String lastName;
private String email;
private String password;
private int gender;
private Timestamp birthday;
private Timestamp diagnoseDate;
private Timestamp created;
private UserType userType;
#Transient
private ArrayList<Task> lastSubmittedTasks;
public UserType getUserType() {
return userType;
}
public void setUserType(UserType userType) {
this.userType = userType;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public Timestamp getBirthday() {
return birthday;
}
public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
}
public void setBirthday(long birthday) {
this.birthday = new Timestamp(birthday);
}
public Timestamp getDiagnoseDate() {
return diagnoseDate;
}
public void setDiagnoseDate(Timestamp diagnoseDate) {
this.diagnoseDate = diagnoseDate;
}
public void setDiagnoseDate(long diagnoseDate) {
this.diagnoseDate = new Timestamp(diagnoseDate);
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public void setCreated(long created) {
this.created = new Timestamp(created);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public ArrayList<Task> getLastSubmittedTask() {
return lastSubmittedTasks;
}
public void setLastSubmittedTasks(ArrayList<Task> lastSubmittedTasks) {
this.lastSubmittedTasks = lastSubmittedTasks;
}
}
#RequestMapping(value = "/questionnaires", method = RequestMethod.POST)
#ResponseBody
public String createQuestionnaires(#RequestBody String body, HttpSession session) {
EntityManager em = emf.createEntityManager();
long patientId = (long) session.getAttribute("patientId");
try {
Questionnaire questionnaire = gson.fromJson(body, Questionnaire.class);
questionnaire.setPatientId(patientId);
questionnaire.setCreated(new Timestamp(System.currentTimeMillis()));
em.getTransaction().begin();
em.persist(questionnaire);
em.getTransaction().commit();
return "{\"status\": \"OK\", \"id\": " + questionnaire.getId() + "}";
} finally {
em.close();
}
}
Related
I have a many-to-many relationship (Car & driver) How, when deleting a Driver, delete a link in the driver_car table and delete cars that were bound to this driver, and vice versa, when deleting a car, simply delete a car and links in the driver_car table that are not associated with this by car?
My BaseEntity:
#MappedSuperclass
public abstract class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#Temporal(TemporalType.TIMESTAMP)
private Date updated;
private Boolean visible;
#Column(name = "image_url")
private String imageUrl;
public BaseEntity() {
this.created = new Date();
this.updated = new Date();
this.visible = true;
}
#PreUpdate
public void preUpdate() {
this.updated = new Date();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
My Driver:
#Entity
#Table(name = "drivers")
public class Driver extends BaseEntity {
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
private String notes;
private double balance;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "driver_car",
joinColumns = #JoinColumn(name = "driver_id"),
inverseJoinColumns = #JoinColumn(name = "car_id"))
private Set<Car> cars;
public Driver() {
super();
this.cars = new HashSet<>();
}
public Set<Car> getCars() {
return cars;
}
public void setCars(Set<Car> cars) {
this.cars = cars;
}
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 getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
My Car:
#Entity
#Transactional
public class Car extends BaseEntity {
#Column(name = "cars_name")
private String carName;
private String color;
#Column(name = "engine_of_capacity")
private double engineCapacity;
#Column(name = "years_of_issue")
private Integer yearsOfIssue;
#Column(name = "car_number")
private String carNumber;
#ManyToMany(mappedBy = "cars", cascade = CascadeType.ALL)
private Set<Driver> drivers;
public Car() {
super();
drivers = new HashSet<>();
}
public Set<Driver> getDrivers() {
return drivers;
}
public void setDrivers(Set<Driver> drivers) {
this.drivers = drivers;
}
public String getCarNumber() {
return carNumber;
}
public void setCarNumber(String carNumber) {
this.carNumber = carNumber;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getEngineCapacity() {
return engineCapacity;
}
public void setEngineCapacity(double engineCapacity) {
this.engineCapacity = engineCapacity;
}
public Integer getYearsOfIssue() {
return yearsOfIssue;
}
public void setYearsOfIssue(Integer yearsOfIssue) {
this.yearsOfIssue = yearsOfIssue;
}
}
Delete Car:
#Override
public void delete(Long id) {
entityManager.createQuery("delete from Car s where s.id = :id")
.setParameter("id", id)
.executeUpdate();
}
Delete Driver:
#Override
public void delete(Long id) {
entityManager.createQuery("delete from Driver d where d.id = :id")
.setParameter("id", id)
.executeUpdate();
}
One should be very cautious about using CascadeType.ALL for #ManyToMany associations, since this might yield surprising results as described e.g. here:
https://thorben-janssen.com/best-practices-for-many-to-many-associations-with-hibernate-and-jpa/#The_CascadeType_you_should_avoid_at_all_costs
In the best case, it only creates performance issues, but in the worst case, it might also remove more records than you intended.
So a better way would be e.g. to have a dedicated service logic which specifies exactly which entities are to be deleted and which of course also takes care of synchronizing both sides of the association.
This way there can also be a simple check whether a previously associated Car has no more associated Drivers after one was deleted, so that the "orphan" Car can then be deleted as well.
I have User and Employee tables on MySQL, and there is employeeId as foreign key in User table.
Now I need to get Employees who do not have User.
I write this SQL in MySQL Workbench, this works exactly how I want:
SELECT * FROM HUMANRESOURCE.EMPLOYEE E LEFT JOIN AUTHORIZE.USER U
ON U.EMPLOYEEOBJID = E.OBJID
WHERE U.EMPLOYEEOBJID is NULL;
But when I try to implement this SQL as JPA query, it returns nothing. Here is JPA Query:
Query query = em.createQuery("SELECT e FROM Employee e LEFT JOIN User u
WHERE u.employee.objid = e.objid
AND u.employee IS NULL");
And here is truely working JPA Query that I use for getting Employees who have user:
Query query = em.createQuery("SELECT e FROM Employee e INNER JOIN User u
WHERE u.employee.objid = e.objid");
What am I doing wrong here?
Update for entity classes:
Base.java
package com.kadir.entity;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
#Cacheable
#MappedSuperclass
public abstract class Base {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "OBJID")
private BigInteger objid;
#Column(name = "CREATEDBY")
private String createdby;
#Column(name = "CREATEDDATE")
private Timestamp createddate;
#Version
#Column(name = "ROWVERSION")
private Integer rowversion;
#Column(name = "UPDATEDBY")
private String updatedby;
#Column(name = "UPDATEDDATE")
private Timestamp updateddate;
#Column(name = "ARCHIVED", columnDefinition = "int default 0")
private int archived;
public BigInteger getObjid() {
return this.objid;
}
public void setObjid(BigInteger objid) {
this.objid = objid;
}
public String getCreatedby() {
return this.createdby;
}
public void setCreatedby(String createdby) {
this.createdby = createdby;
}
public Date getCreateddate() {
return this.createddate;
}
public void setCreateddate(Timestamp createddate) {
this.createddate = createddate;
}
public Integer getRowversion() {
return this.rowversion;
}
public void setRowversion(Integer rowversion) {
this.rowversion = rowversion;
}
public String getUpdatedby() {
return this.updatedby;
}
public void setUpdatedby(String updatedby) {
this.updatedby = updatedby;
}
public Timestamp getUpdateddate() {
return this.updateddate;
}
public void setUpdateddate(Timestamp updateddate) {
this.updateddate = updateddate;
}
public int getArchived() {
return archived;
}
public void setArchived(int archived) {
this.archived = archived;
}
}
Employee.java
package com.kadir.entity.humanresource;
import com.kadir.entity.corporation.Company;
import com.kadir.entity.Base;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the EMPLOYEE database table.
*
*/
#Cacheable
#Entity
#Table(name = "EMPLOYEE", schema = "HUMANRESOURCE")
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")
public class Employee extends Base implements Serializable {
private static final long serialVersionUID = 1L;
#ManyToOne
#JoinColumn(name = "COMPANYOBJID")
private Company company;
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "GENDER")
private int gender;
#Column(name = "EMAIL")
private String email;
#Column(name = "PHONE")
private String phone;
#Column(name = "LASTNAME")
private String lastname;
public Employee() {
}
public Company getCompany() {
return this.company;
}
public void setCompany(Company company) {
this.company = company;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public int getGender() {
return this.gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
User.java
package com.kadir.entity.authorize;
import com.kadir.entity.Employee;
import com.kadir.entity.Base;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the USER database table.
*
*/
#Cacheable
#Entity
#Table(name="USER", schema="AUTHORIZE")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User extends Base implements Serializable {
private static final long serialVersionUID = 1L;
#OneToOne
#JoinColumn(name="EMPLOYEEOBJID")
private Employee employee;
#Column(name="NAME")
private String name;
#Column(name="PASSWORD")
private String password;
public User() {
}
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
EclipseLink has support for the ON clause, so try using
"SELECT e FROM Employee e LEFT JOIN User u on u.employee = e WHERE u.employee IS NULL"
You can also use exist and a subquery:
"select e from Employee e where not exists (select 1 from User u where u.employee = e)"
In my case, I'm using Apache OpenJPA.
Query should be something like this:
SELECT e FROM Employee e LEFT JOIN e.user u WHERE u.employeeId IS NULL
I had similar error. I had conditional OneToOne relation. I fixed problem like that.
#Query("SELECT e FROM Employee e LEFT OUTER JOIN User u ON u = e.user " +
"WHERE (u IS NULL OR e.condition = :conditionValue) ")
I have 3 classes Appointment,Patient and Doctor.Appointment have 1to1 reletionship with both Patient and Doctor.
When i insert a appointment object in database everytime the new patient and doctor object is also inserted in the database.
Patient Class:
#Entity
#Table(name = "Patient")
public class Patient {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int patientId;
private String firstName;
private String lastName;
private int age;
private String cnic;
private String contactNumber;
private String homeNumber;
private String country;
private String city;
private String town;
private String streetNo;
private String houseNo;
private String email;
private String username;
private String password;
public int getPatientId() {
return patientId;
}
public void setPatientId(int patientId) {
this.patientId = patientId;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCnic() {
return cnic;
}
public void setCnic(String cnic) {
this.cnic = cnic;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getHomeNumber() {
return homeNumber;
}
public void setHomeNumber(String homeNumber) {
this.homeNumber = homeNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId(){
return patientId;
}
public Patient getPatient(){
return this;
}
}
Doctor Class :
#Entity
#Table(name = "Doctor")
public class Doctor extends Users {
private String specialization;
public String getSpecialization() {
return specialization;
}
public void setSpecialization(String specialization) {
this.specialization = specialization;
}
}
Appointment Class:
#Entity
public class AppointmentClass {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int appointmentId;
private int appointmentDay;
private int appointmentTime;
#OneToOne (cascade=CascadeType.ALL,fetch = FetchType.EAGER)
private Patient patient;
#OneToOne (cascade=CascadeType.ALL,fetch = FetchType.EAGER)
private Doctor doctor;
public int getAppointmentId() {
return appointmentId;
}
public void setAppointmentId(int appointmentId) {
this.appointmentId = appointmentId;
}
public int getAppointmentDay() {
return appointmentDay;
}
public void setAppointmentDay(int appointmentDay) {
this.appointmentDay = appointmentDay;
}
public int getAppointmentTime() {
return appointmentTime;
}
public void setAppointmentTime(int appointmentTime) {
this.appointmentTime = appointmentTime;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
}
Service Class:
public class AppointmentPatientService {
private SessionFactory sessionFactory = null;
public AppoinmentPatient createNewAppointment(AppoinmentPatient appointment){
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Patient patient = new Patient();
Doctor doctor = new Doctor();
patient = (Patient)(appointment).getPatient();
AppointmentClass appointment1 = new AppointmentClass();
appointment1 = (AppointmentClass)(appointment).getAppointment();
doctor = (Doctor)appointment.getDoctor();
appointment1.setPatient(patient);
appointment1.setDoctor(doctor);
session.beginTransaction();
session.save(appointment1);
session.getTransaction().commit();
session.close();
}catch(Exception ex){
ex.printStackTrace();
}
return appointment;
}
}
Is there any way that when i save the appointment object the new objects of patient and doctor not save to the database.
I shall be thankful :)
I think your relationship type should not be OneToOne from neither the doctor or the patient, because one doctor can have many appointments and one patient can have many appointments. So it should be OneToMany from both sides, in which case a new doctor and a new patient won't be created for each new appointment if you supply the appointment with correct existing doctor and patient ID-s.
In the class AppointmentClass, change the cascade settings.
You can use cascade=CascadeType.NONE, This will make sure that the associated Patient and Doctor objects are not saved to database.
You can see all other values of CascadeType to find the right choice for you.
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;
I have created one model class
#Entity
#Table(name = "tblcoustomer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "tblcoustomer_cid_gen")
#SequenceGenerator(name = "tblcoustomer_cid_gen", sequenceName = "tblcoustomer_cid_seq")
#Column(name = "cid")
private int id;
#ManyToOne(targetEntity = FinancialMonth.class, fetch = FetchType.EAGER)
#JoinColumn(name = "monthId", nullable = false)
private FinancialMonth monthId;
#ManyToOne(targetEntity = Company.class, fetch = FetchType.EAGER)
#JoinColumn(name = "companyId", nullable = false)
private Company companyId;
#ManyToOne(targetEntity = CustomerType.class, fetch = FetchType.EAGER)
#JoinColumn(name = "customerType", nullable = false)
private CustomerType customerType;
private String firstName;
private String lastName;
private String gender;
private int age;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public FinancialMonth getMonthId() {
return monthId;
}
public void setMonthId(FinancialMonth monthId) {
this.monthId = monthId;
}
public Company getCompanyId() {
return companyId;
}
public void setCompanyId(Company companyId) {
this.companyId = companyId;
}
public CustomerType getCustomerType() {
return customerType;
}
public void setCustomerType(CustomerType customerType) {
this.customerType = customerType;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
now when I am trying to load this object using #ModelAttribute I am getting error
#RequestMapping(value = "/saveCustomer")
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("custome") Customer customer) {
Map<String, Object> model = new HashMap<String, Object>();
return new ModelAndView("addCustomer", model);
}
I konw I have to override #initBinder but how do I bind can any one please help me I am getting this error
I can not answer your question without knowing the exception, but there is an typo in your code that may cause an problem:
you have:
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("custome") Customer customer)
But I think it should be model attribute "customer" with an "r" at the end.
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("customer") Customer customer)