Why hibernate update after insert the record in table - java

I have two Entities CompanyDetail and DriverDetail
CompanyDetail
package com.javarnd.pns.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
#Entity
#Table(name="company_detail")
public class CompanyDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="company_id")
private long companyId;
#Column(name="company_name")
private String companyName;
#Column(name="pan_no")
private String panNo;
private String website;
private String email;
#Column(name="conntact_no")
private String contactNo;
#OneToMany(cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name = "COMPANY_VEHICLE_DETAIL", joinColumns = #JoinColumn(name = "company_id"), inverseJoinColumns = #JoinColumn(name = "vehicle_id"))
private List<Vehicle> vehicleList;
#OneToMany(cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name = "COMPANY_DRIVER_DETAIL", joinColumns = #JoinColumn(name = "company_id"), inverseJoinColumns = #JoinColumn(name = "driver_id"))
private List<DriverDetail> driverList;
#Column(name="type")
private String companyType;
public long getCompanyId() {
return companyId;
}
public void setCompanyId(long companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getPanNo() {
return panNo;
}
public void setPanNo(String panNo) {
this.panNo = panNo;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getCompanyType() {
return companyType;
}
public void setCompanyType(String companyType) {
this.companyType = companyType;
}
public List<Vehicle> getVehicleList() {
return vehicleList;
}
public void setVehicleList(List<Vehicle> vehicleList) {
this.vehicleList = vehicleList;
}
public List<DriverDetail> getDriverList() {
return driverList;
}
public void setDriverList(List<DriverDetail> driverList) {
this.driverList = driverList;
}
}
DriverDetail
package com.javarnd.pns.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
#Entity
public class DriverDetail {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="driver_id")
private long id;
private String name;
#Column(name="contact_no")
private String contactNo;
#Column(name="license_no")
private String licenseNo;
#ManyToMany(mappedBy="availableDriverList",cascade=CascadeType.ALL)
private List<Vehicle> asignedVehicle;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="company_id")
private CompanyDetails companyDetail;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactNo() {
return contactNo;
}
public String getLicenseNo() {
return licenseNo;
}
public void setLicenseNo(String licenseNo) {
this.licenseNo = licenseNo;
}
public List<Vehicle> getAsignedVehicle() {
return asignedVehicle;
}
public void setAsignedVehicle(List<Vehicle> asignedVehicle) {
this.asignedVehicle = asignedVehicle;
}
public CompanyDetails getCompanyDetail() {
return companyDetail;
}
public void setCompanyDetail(CompanyDetails companyDetail) {
this.companyDetail = companyDetail;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
}
MAIN TEST CLASS
package com.javarnd.pns.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.javarnd.pns.model.CompanyDetails;
import com.javarnd.pns.model.DriverDetail;
import com.javarnd.pns.service.CompanyDetailService;
import com.javarnd.pns.service.DriverDetailService;
public class TestPns {
public static void main(String[] args) {
CompanyDetailService cdService=new CompanyDetailService();
CompanyDetails cd=new CompanyDetails();
List<DriverDetail>ddList=new ArrayList<>();
DriverDetail driver=new DriverDetail();
DriverDetailService dds=new DriverDetailService();
Scanner kb=new Scanner(System.in);
System.out.println("Enter name:");
String cname=kb.nextLine();
driver.setName(cname);
System.out.println("Enter Compnay Id");
long companyId=kb.nextLong();
cd.setCompanyId(companyId);
System.out.println("Enter License:");
String license=kb.next();
driver.setLicenseNo(license);
System.out.println("Enter Contact");
String contact=kb.nextLine();
driver.setContactNo(contact);
ddList.add(driver);
cd.setDriverList(ddList);
driver.setCompanyDetail(cd);
dds.save(driver);
System.out.println("saved");
}
}
And now I tested that from my above main class, it printed the log in which it insert the values in DriverDetail table and update the company_detail table and at last then insert the values in COMPANY_DRIVER_DETAIL table
Finally the console LOG
Hibernate:
select
next_val as id_val
from
hibernate_sequence for update
Hibernate:
update
hibernate_sequence
set
next_val= ?
where
next_val=?
Hibernate:
/* insert com.javarnd.pns.model.DriverDetail
*/ insert
into
DriverDetail
(company_id, contact_no, license_no, name, driver_id)
values
(?, ?, ?, ?, ?)
Hibernate: //HERE IT IS UPDATING THE CompanyDetail , MAIKING ALL FIELDS NULL
/* update
com.javarnd.pns.model.CompanyDetails */ update
company_detail
set
company_name=?,
type=?,
conntact_no=?,
email=?,
pan_no=?,
website=?
where
company_id=?
Hibernate:
/* delete collection com.javarnd.pns.model.CompanyDetails.driverList */ delete
from
COMPANY_DRIVER_DETAIL
where
company_id=?
Hibernate:
/* delete collection com.javarnd.pns.model.CompanyDetails.vehicleList */ delete
from
COMPANY_VEHICLE_DETAIL
where
company_id=?
Hibernate:
/* insert collection
row com.javarnd.pns.model.CompanyDetails.driverList */ insert
into
COMPANY_DRIVER_DETAIL
(company_id, driver_id)
values
(?, ?)
After this everything goes fine except that the data corresponding of the particular id in Country_detail table is all NULL, and i don't want to fetch the data on behalf of id and then pass the object to driver.setCompanyDetail(cd); because it somehow degrades the performance, i need to know the way to resist this unnecessary update.

Related

How to handle many-to-many relationship in Hibernate with non-primary key?

I have two objects - Role and Privilege. They have a many-to-many relationship. The code of each object is shown below.
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
#Entity
#Table(name = "rml_privilege")
public class RmlPrivilege extends RmlBase implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6810028565979325754L;
public static final String ATTR_NAME = "name";
#Column(name="name",nullable=false,unique=true)
private String name;
#Column(name="description")
private String description;
public String getName() {
return name;
}
public void setName(String privilege) {
this.name = privilege;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
This is the RmlRole file.
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "rml_role")
public class RmlRole extends RmlBase {
public final static String ATTR_ORG = "org.id";
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "organization")
private RmlOrganization organization;
//TODO: In case of LAZY loading, recieve an error
#ManyToMany(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinTable(name = "rml_role_privilege", joinColumns = {
#JoinColumn(name = "role", referencedColumnName = "id") }, inverseJoinColumns = {
#JoinColumn(name = "privilege", referencedColumnName = "name") })
Set<RmlPrivilege> privileges;
public RmlOrganization getOrganization() {
return organization;
}
public void setOrganization(RmlOrganization organization) {
this.organization = organization;
}
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 Set<RmlPrivilege> getPrivileges() {
return privileges;
}
public void setPrivileges(Set<RmlPrivilege> privileges) {
this.privileges = privileges;
}
}
When I try to get the RmlRole object, I end up getting the "privileges' variable to be blank. I expect the privilege object set to be prepared. I am doing it wrong somewhere but unable to identify.
My Hibernate version: 5
Java 1.8
Spring Boot application
Any help would be highly appreciated.

org.hibernate.WrongClassException: Object [id=null] was not of the specified subclass

I have data model like below
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import org.hibernate.annotations.DiscriminatorOptions;
#SuppressWarnings("deprecation")
#Entity
#Table
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name="DTYPE", discriminatorType=DiscriminatorType.INTEGER)
#DiscriminatorValue("0")
#DiscriminatorOptions(force=true)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
public Employee() {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "EMPLOYEE_ID")
private int empID;
private String firstName;
private String lastName;
private Integer age;
private String email;
private String city;
private String phNum;
public String getPhNum() {
return phNum;
}
public void setPhNum(String phNum) {
this.phNum = phNum;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Patient.java
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.DiscriminatorOptions;
import org.hibernate.validator.constraints.NotEmpty;
#SuppressWarnings("deprecation")
#Entity
#Table
#PrimaryKeyJoinColumn(name = "EMPLOYEE_ID")
#DiscriminatorValue("6")
public class Patient extends Employee {
private static final long serialVersionUID = 1L;
#NotEmpty(message = "DOJ cannot be null")
private String doj;
private String primaryDoctor;
public String getPrimaryDoctor() {
return primaryDoctor;
}
public void setPrimaryDoctor(String primaryDoctor) {
this.primaryDoctor = primaryDoctor;
}
public String getDoj() {
return doj;
}
public void setDoj(String doj) {
this.doj = doj;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy = "patient", fetch = FetchType.LAZY)
private List<Encounter> encounterList;
public List<Encounter> getEncounterList() {
return encounterList;
}
public void setEncounterList(List<Encounter> encounterList) {
this.encounterList = encounterList;
}
}
Hibernate query at runtime
select useraccoun0_.empID as empID1_13_2_, useraccoun0_.EMPLOYEE_ID as EMPLOYEE6_13_2_,
useraccoun0_.fullName as fullName2_13_2_, useraccoun0_.password as password3_13_2_,
useraccoun0_.role as role4_13_2_, useraccoun0_.userName as userName5_13_2_,
employee1_.EMPLOYEE_ID as EMPLOYEE2_2_0_, employee1_.age as age3_2_0_,
employee1_.city as city4_2_0_, employee1_.email as email5_2_0_, employee1_.firstName as firstNam6_2_0_,
employee1_.lastName as lastName7_2_0_, employee1_.phNum as phNum8_2_0_, employee1_4_.doj as doj1_11_0_,
employee1_4_.primaryDoctor as primaryD2_11_0_, employee1_5_.specialization as speciali1_0_0_,
employee1_.DTYPE as DTYPE1_2_0_, encounterl2_.EMPLOYEE_ID as EMPLOYEE4_3_4_,
encounterl2_.EID as EID1_3_4_, encounterl2_.EID as EID1_3_1_, encounterl2_.labTest_testID as labTest_2_3_1_,
encounterl2_.medication_mid as medicati3_3_1_, encounterl2_.EMPLOYEE_ID as EMPLOYEE4_3_1_,
encounterl2_.vitalSign_EID as vitalSig5_3_1_ from UserAccount useraccoun0_
left outer join Employee employee1_ on useraccoun0_.EMPLOYEE_ID=employee1_.EMPLOYEE_ID
left outer join Pharmacist employee1_1_ on employee1_.EMPLOYEE_ID=employee1_1_.EMPLOYEE_ID
left outer join Nurse employee1_2_ on employee1_.EMPLOYEE_ID=employee1_2_.EMPLOYEE_ID
left outer join LabAssistant employee1_3_ on employee1_.EMPLOYEE_ID=employee1_3_.EMPLOYEE_ID
left outer join Patient employee1_4_ on employee1_.EMPLOYEE_ID=employee1_4_.EMPLOYEE_ID
left outer join Doctor employee1_5_ on employee1_.EMPLOYEE_ID=employee1_5_.EMPLOYEE_ID
left outer join Encounter encounterl2_ on employee1_.EMPLOYEE_ID=encounterl2_.EMPLOYEE_ID
where useraccoun0_.empID=4
In this query Discriminator column(DTYPE) is coming and its value is coming as 6. But it is giving me below exception
org.hibernate.WrongClassException: Object [id=null] was not of the specified subclass [com.*.*.Employee]: the class of the given object did not match the class of persistent copy
So not sure why it is giving me this exception and why id is coming as null.

How to resolve the problem of foreign key of being zero all time when data inserted to tables using spring boot?

User.java
package com.spring.demo.model;
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.Lob;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="user_id")
private int id;
private String fName;
private String lName;
#Column(unique=true,nullable=true)
private String email;
#Column(unique=true,nullable=true)
private long mobile;
private Date dob;
#Lob
private byte[] image;
#Transient
private String base64Image;
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="userCredential_id")
private UserCredential userCredential;
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="add_id")
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public UserCredential getUserCredential() {
return userCredential;
}
public void setUserCredential(UserCredential userCredential) {
this.userCredential = userCredential;
}
}
UserCredential.java
package com.spring.demo.model;
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 com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="usercredential")
public class UserCredential {
#Id
#Column(name="credential_id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(unique=true,nullable=true)
private String username;
private String password;
private String cnfrmpassword;
#JsonIgnore
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="user_id",nullable=true)
private User user;
public UserCredential() {
super();
// TODO Auto-generated constructor stub
}
public UserCredential(int id, String username, String password, String cnfrmpassword, User user) {
super();
this.id = id;
this.username = username;
this.password = password;
this.cnfrmpassword = cnfrmpassword;
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getCnfrmpassword() {
return cnfrmpassword;
}
public void setCnfrmpassword(String cnfrmpassword) {
this.cnfrmpassword = cnfrmpassword;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Address.java
package com.spring.demo.model;
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 com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="address")
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="add_id")
private int id;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="house_no")
private String h_no;
#JsonIgnore
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="user_id", nullable=true)
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getH_no() {
return h_no;
}
public void setH_no(String h_no) {
this.h_no = h_no;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Here we have user as a parent table and (usercredential and address) are child classes in a relationship. When I insert data into tables then every primary key automatically incremented and get the appropriate value while the foreign key (user_id) always remains zero.
https://i.stack.imgur.com/Pivlm.jpg
https://i.stack.imgur.com/fAPth.jpg
https://i.stack.imgur.com/l37mr.jpg
My concern is user_id(foreign key) in child tables should not be null and equals to primary key(user_id) in parent table. Please look for every cascading(delete, update) operation should be implemented well on table.
Further information I am using Json for inserting data into tables.
{
"fName":"sur kumst",
"lName":"adfdf",
"mobile":45106,
"email":"ksusjasd1sd#gmail.com",
"dob":"2012-04-23T18:25:43.511Z",
"address":{
"city":"noida",
"state":"up",
"h_no":"1243"
},
"userCredential":{
"username":"kr0302",
"password":"12345",
"cnfrmpassword":"12345"
}
}
The issue is with the back reference. Hibernate cannot maintain this for you. Say you save your user object. it creates a credential row and generates id. it creates address and id. it updates the cred_id and add_id on the user object and then creates a row for it and generates id and returns that value. at this point you need to add your user object to credential and address and save those again.
It seems you are trying to model two bidirectional relationships:
User <-> UserCredentials and:
User <-> UserAddress.
But what you are really creating the following four relationships:
User -> UserCredentials
User <- UserCredentials
User -> UserAddress
User <- UserAddress
In order to fix this you need to use mappedBy. See this question for reference.

How to map database hql

I have database with 2 simple tables.
cat (category) with id, name.
prod (products) with id, catid, name, price.
I made a query
select pr.id, pr.catid,pr.name, pr.price
FROM prod pr, cat ct
WHERE pr.catid = ct.id AND ct.name = ?
I noticed problem eariler when I use #JoinColumn(name="catid") in prod class.
Repeated column in mapping for entity: goods.prod column: catid
(should be mapped with insert="false" update="false"
I try to use #JoinColumn(name="catid",insertable = false, updatable = false)
but even with this I have cast error.
Ljava.lang.Object; cannot be cast to goods.prod
How can I map database? And do I need to make changes in simplest SQL?
cat class
package goods;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import goods.prod;
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.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="cat")
public class cat implements Serializable {
#Id
#Column(name="id",insertable = false, updatable = false)
private Integer id;
#OneToMany(mappedBy="catmap")
private List<prod> prods;
private static final long serialVersionUID = -4147058093508047162L;
private String name;
public cat() {
}
public cat(int id, String Name) {
this.id = id;
this.name = Name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String Name) {
this.name = Name;
}
}
prod class
package goods;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import goods.cat;
import java.io.Serializable;
#Entity
#Table(name = "prod")
public class prod implements Serializable {
#Id #GeneratedValue
#Column(name="id",insertable = false, updatable = false)
private Long id;
#ManyToOne (fetch=FetchType.LAZY)
#JoinColumn(name="catid",insertable = false, updatable = false)
private cat catmap;
private Integer catid;
private String name;
private Integer price;
public prod() {
}
public prod(Long id, Integer catid, String name, Integer price) {
this.id = id;
this.catid = catid;
this.name = name ;
this.price = price;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
public Integer getcatid() {
return catid;
}
public void setcatid(Integer catid) {
this.catid = catid;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public Integer getprice() {
return price;
}
public void setprice(Integer price) {
this.price = price;
}
}
func
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
//Query query = session.createQuery("FROM prod");
Query query = session.createQuery("select pr.id, pr.catid,pr.name, pr.price FROM prod pr, cat ct WHERE pr.catid = ct.id AND ct.name = ?");
//Query query = session.createQuery("from prod pr join pr.cat ct with pr.catid=ct.id where ct.name=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}

How Filter data When key attribute is in child Table +spring mvc and hibernate

There are 2 table, Parent is MeetingTypes Child is Meetings they have1 : m mapping
Meeting has releaseID atribute so i want to filter its by releaseID .but problem is, its in Child Table...
If it is Parent Table we can do it simply and it is working
Query query = session.getCurrentSession().createQuery("from MeetingTypes where releaseID= :releaseID");
query.setParameter("releaseID", releaseID);
List list = query.list();
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
I tried it this way
Query query = session.getCurrentSession().createSQLQuery(
"from MeetingTypes mt join mt.Meetings m " +
"where m.releaseID = :releaseID");
query.setParameter("releaseID", releaseID);
return query.list();
But give bellow Erro
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from MeetingTypes mt join mt.Meetings m where m.releaseID = 192' at
line 1
relevant tabales
package pearson.dashboard.model;
import java.util.List;
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.OneToMany;
#Entity
public class MeetingTypes {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int meetingTypeID;
#Column
private String typeName;
#OneToMany(mappedBy = "meetingTypes",fetch = FetchType.EAGER)
private List<Meetings> meetings;
public List<Meetings> getMeetings() {
return meetings;
}
public void setMeetings(List<Meetings> meetings) {
this.meetings = meetings;
}
public MeetingTypes() {
// TODO Auto-generated constructor stub
}
public MeetingTypes(int meetingTypeID, String typeName
) {
super();
this.meetingTypeID = meetingTypeID;
this.typeName = typeName;
}
public int getMeetingTypeID() {
return meetingTypeID;
}
public void setMeetingTypeID(int meetingTypeID) {
this.meetingTypeID = meetingTypeID;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
package pearson.dashboard.model;
import java.util.Date;
import java.util.List;
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.ManyToOne;
import org.springframework.context.annotation.Lazy;
#Entity
public class Meetings {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int meetingID;
#Column
private Date sheduleTime;
#Column
private String meetingHeading;
#Column
private String comment;
#Column
private String roomName;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "meetingTypeID")
private MeetingTypes meetingTypes;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "releaseID")
private Releases releases;
public Releases getReleases() {
return releases;
}
public void setReleases(Releases releases) {
this.releases = releases;
}
public MeetingTypes getMeetingTypes() {
return meetingTypes;
}
public void setMeetingTypes(MeetingTypes meetingTypes) {
this.meetingTypes = meetingTypes;
}
public Meetings() {
// TODO Auto-generated constructor stub
}
public Meetings(int meetingID, Date sheduleTime, String meetingHeading,
String comment, String roomName) {
super();
this.meetingID = meetingID;
this.sheduleTime = sheduleTime;
this.meetingHeading = meetingHeading;
this.comment = comment;
this.roomName = roomName;
}
public int getMeetingID() {
return meetingID;
}
public void setMeetingID(int meetingID) {
this.meetingID = meetingID;
}
public Date getSheduleTime() {
return sheduleTime;
}
public void setSheduleTime(Date sheduleTime) {
this.sheduleTime = sheduleTime;
}
public String getMeetingHeading() {
return meetingHeading;
}
public void setMeetingHeading(String meetingHeading) {
this.meetingHeading = meetingHeading;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
}
package pearson.dashboard.model;
import java.util.Date;
import java.util.List;
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.ManyToOne;
import javax.persistence.OneToMany;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
#Entity
public class Releases {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int releaseID;
#Column
private String orcleCode;
#Column
private String status;
#Column
private Date staging;
#Column
private Date cabCall;
#Column
private Date rrr;
#Column
private String remarks;
#Column
private String releaseName;
#Column
private Date prodDate;
#ManyToOne( fetch = FetchType.EAGER)
#JoinColumn(name = "teamID")
private Teams teams;
public Teams getTeams() {
return teams;
}
public void setTeams(Teams teams) {
this.teams = teams;
}
#OneToMany(mappedBy = "releases",fetch = FetchType.EAGER)
#Fetch(value = FetchMode.SUBSELECT)
private List<Meetings> meetings;
public List<Meetings> getMeetings() {
return meetings;
}
public void setMeetings(List<Meetings> meetings) {
this.meetings = meetings;
}
public Releases() {}
public Releases(int releasID, String orcleCode, String status,
Date staging, Date cabCall, Date rrr, String remarks,
String releaseName,Date prodDate) {
super();
this.releaseID = releasID;
this.orcleCode = orcleCode;
this.status = status;
this.staging = staging;
this.cabCall = cabCall;
this.rrr = rrr;
this.remarks = remarks;
this.releaseName = releaseName;
this.prodDate = prodDate;
}
public int getReleaseID() {
return releaseID;
}
public void setReleaseID(int releaseID) {
this.releaseID = releaseID;
}
public String getOrcleCode() {
return orcleCode;
}
public void setOrcleCode(String orcleCode) {
this.orcleCode = orcleCode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStaging() {
return staging;
}
public void setStaging(Date staging) {
this.staging = staging;
}
public Date getCabCall() {
return cabCall;
}
public void setCabCall(Date cabCall) {
this.cabCall = cabCall;
}
public Date getRrr() {
return rrr;
}
public void setRrr(Date rrr) {
this.rrr = rrr;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getReleaseName() {
return releaseName;
}
public void setReleaseName(String releaseName) {
this.releaseName = releaseName;
}
public Date getProdDate() {
return prodDate;
}
public void setProdDate(Date prodDate) {
this.prodDate = prodDate;
}
}
part of Controller******
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pearson.dashboard.dto.NewMeeting;
import pearson.dashboard.service.MeetingService;
import pearson.dashboard.service.MeetingTypeService;
import pearson.dashboard.service.MemberService;
import pearson.dashboard.service.SwarmingScheduleService;
#Controller
public class MeetingTypesController {
#Autowired
private MeetingTypeService meetingTypeService;
//#Autowired
//private MeetingService meetingService;
#Autowired
private SwarmingScheduleService swarmingScheduleService;
#Autowired
private MemberService memberService;
#RequestMapping(value="/detailsPage",method=RequestMethod.POST)
public String getAllmeeting(#ModelAttribute NewMeeting newMeeting,BindingResult result,Map<String, Object> map){
int releaseID = newMeeting.getReleaseID();
map.put("meetingList", meetingTypeService.getAllMeetingTypes(releaseID));
map.put("swarmingScheduleList",swarmingScheduleService.gettAllSwarming() );
map.put("memberList",memberService.gettAllMembers() );
return "details";
}
}
You are using HQL not sql so in hql no keyword like join alternatively you can implement join using objecta.objectb and so on so you have to create your query like below
Query query = session.getCurrentSession().createQuery("FROM MeetingTypes mt WHERE mt.meetings.releases.id = :releaseID");
for more details see the below link
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins-forms
Your HQL query should be like this
Query query = session.getCurrentSession().createQuery("FROM MeetingTypes AS mt WHERE mt.meetings.releases.id = :releaseID");
query.setParameter("releaseID", releaseID);
return query.list();
hope this will solve your problem.
hopefully your Releases Entity something like
#Entity
#Table(name="meetings")
public class Meetings {
#Id
#Column(name="meetings_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
//setter & getters
}
also you have not mentioned your name parameter in #Table() annotation is your table name is same as class name ?
#Entity
The #Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
#Column
The #Column annotation is used to specify the details of the column to which a field or property will be mapped. If the #Column annotation is not specified by default the property name will be used as the column name.
#Table
The #Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If #Table annotation is not specified then Hibernate will by default use the class name as the table name.
createQuery() VS createSQLQuery()
createQuery()
Create a new instance of Query for the given HQL query string.
createSQLQuery()
Create a new instance of SQLQuery for the given SQL query string.

Categories

Resources