QueryException in Hibernate - java

I am using the following bean class
package com.hibernatemappingfile;
import java.io.Serializable;
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="SKILL_SET")
public class SkillSet implements Serializable{
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Column(name="COMPUTER_SKILLS")
private String computer_skills;
#Column(name="TRAININGS_ATTENDED")
private String trainings_attended;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "USER_ID")
private EmployeeMaster employee;
public EmployeeMaster getEmployee() {
return employee;
}
public void setEmployee(EmployeeMaster employee) {
this.employee = employee;
}
public String getComputer_skills() {
return computer_skills;
}
public void setComputer_skills(String computer_skills) {
this.computer_skills = computer_skills;
}
public String getTrainings_attended() {
return trainings_attended;
}
public void setTrainings_attended(String trainings_attended) {
this.trainings_attended = trainings_attended;
}
}
and my hql query is
SELECT t1.trainings_attended,t2.workingstatus
FROM SkillSet t1, EmployeeStatus t2,EmployeeMaster em
WHERE t1.trainings_attended=:trainings_attended AND t1.USER_ID = t2.USER_ID
but i am getting the following exception
SEVERE: Servlet.service() for servlet [sdnext] in context with path [/sdnext] threw exception [Request processing failed; nested exception is org.hibernate.QueryException: could not resolve property: USER_ID of: com.vrnda.hibernatemappingfile.SkillSet [SELECT t1.trainings_attended,t2.workingstatus FROM com.vrnda.hibernatemappingfile.SkillSet t1, com.vrnda.hibernatemappingfile.EmployeeStatus t2,com.vrnda.hibernatemappingfile.EmployeeMaster em WHERE t1.trainings_attended=:trainings_attended AND t1.USER_ID = t2.USER_ID]] with root cause
org.hibernate.QueryException: could not resolve property: USER_ID of: com.vrnda.hibernatemappingfile.SkillSet [SELECT t1.trainings_attended,t2.workingstatus FROM com.vrnda.hibernatemappingfile.SkillSet t1, com.vrnda.hibernatemappingfile.EmployeeStatus t2,com.vrnda.hibernatemappingfile.EmployeeMaster em WHERE t1.trainings_attended=:trainings_attended AND t1.USER_ID = t2.USER_ID]
How to get the user_id of skillset table in select statement.i have tried with t1.em.USER_ID but not working.

try JOIN t1.employee employee and then you will have access to employee.user_id

Related

No property 'tutorial' found for type 'Integer' Traversed path: Commenti.id

I have the following error... I want to retrieve the properties of one Tutorial from a comment but Spring don't allow me to do that. The relationship is a #ManyToOne... How can i retrieve data of a single Tutorial starting from a comment? Also, how can I retrieve a single Comment? I tried to do with Optional but I get a 406 error or worse. Can someone tell me why I get this exception?
Type Exception Report
Message Servlet.init() for servlet [dispatcher] threw exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [dispatcher] threw exception
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'relazioniOne': Unsatisfied dependency expressed through field 'cmRep'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commentiRepository' defined in it.relazioni.repository.one.CommentiRepository defined in #EnableJpaRepositories declared on AppConfig: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract it.relazioni.one.Tutorial it.relazioni.repository.one.CommentiRepository.findByidTutorial(java.lang.Integer); Reason: Failed to create query for method public abstract it.relazioni.one.Tutorial it.relazioni.repository.one.CommentiRepository.findByidTutorial(java.lang.Integer)! No property 'tutorial' found for type 'Integer' Traversed path: Commenti.id.; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract it.relazioni.one.Tutorial it.relazioni.repository.one.CommentiRepository.findByidTutorial(java.lang.Integer)! No property 'tutorial' found for type 'Integer' Traversed path: Commenti.id.
java.lang.IllegalArgumentException: Failed to create query for method public abstract it.relazioni.one.Tutorial it.relazioni.repository.one.CommentiRepository.findByidTutorial(java.lang.Integer)! No property 'tutorial' found for type 'Integer' Traversed path: Commenti.id.
org.springframework.data.mapping.PropertyReferenceException: No property 'tutorial' found for type 'Integer' Traversed path: Commenti.id.
Tutorial Class
package it.relazioni.one;
import java.util.ArrayList;
import java.util.List;
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.OneToMany;
#Entity
public class Tutorial {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(length = 50, nullable = false)
private String titolo;
#Column(length = 255, nullable = false)
private String descrizione;
#Column
private boolean pubblicato;
#OneToMany(mappedBy = "tutorial", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Commenti> listaComm = new ArrayList<Commenti>();
//COSTRUTTORI
public Tutorial(String titolo, String descrizione, boolean pubblicato) {
super();
this.titolo = titolo;
this.descrizione = descrizione;
this.pubblicato = pubblicato;
}
public Tutorial() {
super();
}
public Tutorial(Integer id, String titolo, String descrizione, boolean pubblicato, List<Commenti> listaComm) {
super();
this.id = id;
this.titolo = titolo;
this.descrizione = descrizione;
this.pubblicato = pubblicato;
this.listaComm = listaComm;
}
//GETTER SETTER
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitolo() {
return titolo;
}
public void setTitolo(String titolo) {
this.titolo = titolo;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public boolean isPubblicato() {
return pubblicato;
}
public void setPubblicato(boolean pubblicato) {
this.pubblicato = pubblicato;
}
public List<Commenti> getListaComm() {
return listaComm;
}
public void setListaComm(List<Commenti> listaComm) {
this.listaComm = listaComm;
}
#Override
public String toString() {
return "Tutorial [id=" + id + ", titolo=" + titolo + ", descrizione=" + descrizione + ", pubblicato="
+ pubblicato + ", listaComm=" + listaComm + "]";
}
}
Commenti Class
package it.relazioni.one;
import java.util.ArrayList;
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.ManyToOne;
#Entity
public class Commenti {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column
private String contenuto;
// #Column
// private Integer idTutorial;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name= "idTutorial")
public Tutorial tutorial;
//COSTRUTTORI
public Commenti(String contenuto) {
super();
this.contenuto = contenuto;
}
public Commenti() {
super();
}
//GETTER SETTER
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContenuto() {
return contenuto;
}
public void setContenuto(String contenuto) {
this.contenuto = contenuto;
}
public Tutorial getTutorial() {
return tutorial;
}
public void setTutorial(Tutorial tutorial) {
this.tutorial = tutorial;
}
#Override
public String toString() {
return "Commenti [id=" + id + ", contenuto=" + contenuto + ", tutorial=" + tutorial + "]";
}
}
Tutorial Repository
package it.relazioni.repository.one;
import org.springframework.data.repository.CrudRepository;
import it.relazioni.one.Tutorial;
public interface TutorialRepository extends CrudRepository<Tutorial, Integer> {
}
Commenti Repository
package it.relazioni.repository.one;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import it.relazioni.one.Commenti;
import it.relazioni.one.Tutorial;
public interface CommentiRepository extends CrudRepository <Commenti, Integer>{
Tutorial findByidTutorial(Integer id);
}
Controller
package it.relazioni.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import it.relazioni.one.Commenti;
import it.relazioni.one.Tutorial;
import it.relazioni.repository.one.CommentiRepository;
#Controller
#RequestMapping("/one")
public class RelazioniOne {
#Autowired
private CommentiRepository cmRep;
#ResponseBody
#GetMapping("/test")
public String test() {
return "test";
}
#ResponseBody
#GetMapping("/tutorial")
public String listaTut() {
Tutorial tut = cmRep.findByidTutorial(1);
return tut.toString();
}
}

Getting Exception in thread "main" java.lang.NullPointerException for my hibernate program

Here is my StudentDetails class:
package com.gontuseries.hibernate;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="STUDENT_DETAILS")
public class StudentDetails {
#Id #GeneratedValue( generator= "newGenerator")
#GenericGenerator(name="newGenerator",strategy = "foreign", parameters = {
#Parameter(name="property",value="Student_Info")})
private int rollNo;
private int mobile_no;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name ="rollNo")
private Student_Info student=new Student_Info();
public Student_Info getStudent() {
return student;
}
public void setStudent(Student_Info student) {
this.student = student;
}
public int getMobile_no() {
return mobile_no;
}
public void setMobile_no(int mobile_no) {
this.mobile_no = mobile_no;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}
Here is my Main class :
package com.gontuseries.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.*;
public class Main {
public static void main(String[] args)
{
Student_Info student=new Student_Info();
student.setName("Gontu_Rajesh");
StudentDetails sd=new StudentDetails();
sd.setMobile_no(455656);
sd.setStudent(student);
// student.setRollNo(3);
//Student_Info student2=new Student_Info();
//student2.setName("Gontu_Rajesh_new name");
SessionFactory sessionFactory= new
Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(sd);
//session.save(student2);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
And here is my Student_Info class :
package com.gontuseries.hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="STUDENT_INFORMATION")
public class Student_Info {
#Id #GeneratedValue(strategy = GenerationType.SEQUENCE)
private int rollNo;
private String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
After running Main class I am getting:
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:645)
at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4725)
at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:81)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:691)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:683)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:678)
at com.gontuseries.hibernate.Main.main(Main.java:26)
Any help would be appreciated.
You probably have the same/similar problem with this post:
java.lang.NullPointerException at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:521)
Try replacing this:
#GenericGenerator(name="newGenerator",strategy = "foreign", parameters = {
#Parameter(name="property",value="Student_Info")})
with this:
#GenericGenerator(name="newGenerator",strategy = "foreign", parameters = {
#Parameter(name="property",value="student")})
When using foreign strategy, remember to use the property name instead of the Entity name. The value should have been student instead of Student_Info.

cascade = CascadeType.ALL not updating the child table

These are my pojo class
Orderdetail.java
package online.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "orderdetail")
public class OrderDetail {
#Id
#Column(name="order_detail_id")
private int order_detail_id;
#Column(name="bill")
private float bill;
#ManyToOne
#JoinColumn(name = "p_id" )
private Product p_id;
#ManyToOne
#JoinColumn(name = "o_id" )
private Order o_id;
public int getOrder_detail_id() {
return order_detail_id;
}
public void setOrder_detail_id(int order_detail_id) {
this.order_detail_id = order_detail_id;
}
public float getBill() {
return bill;
}
public void setBill(float bill) {
this.bill = bill;
}
public Product getP_id() {
return p_id;
}
public void setP_id(Product p_id) {
this.p_id = p_id;
}
public Order getO_id() {
return o_id;
}
public void setO_id(Order o_id) {
this.o_id = o_id;
}
}
My Order.java
package online.model;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "ordertable")
public class Order {
#Id
#Column(name = "order_id")
private int order_id;
#OneToMany(mappedBy = "o_id",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<OrderDetail> orderdetail;
#ManyToOne
#JoinColumn(name = "u_id")
private UserDetail u_id;
public UserDetail getU_id() {
return u_id;
}
public void setU_id(UserDetail u_id) {
this.u_id = u_id;
}
#Column(name = "date")
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#Column(name = "totalbill")
private Float totalbill;
public Float getTotalbill() {
return totalbill;
}
public void setTotalbill(Float totalbill) {
this.totalbill = totalbill;
}
public List<OrderDetail> getOrderdetail() {
return orderdetail;
}
public void setOrderdetail(List<OrderDetail> orderdetail) {
this.orderdetail = orderdetail;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
When ever I am trying to save order class I want my orderdetail class also get saved but when I am trying to save the List in order,Is is not getting saved and there is not error provided by hibernate that can help...
Thanks for the help
when i am trying to to persist the order class
Hibernate: select orderdetai_.order_detail_id, orderdetai_.bill as bill7_, orderdetai_.o_id as o3_7_, orderdetai_.p_id as p4_7_ from orderdetail orderdetai_ where orderdetai_.order_detail_id=?
This what I am getting output.
This is my code which save the class
#Override
public boolean payment(String username, Integer ordernumber, Date date,
Float totalbill, List<Integer> list) {
Session session = sessionFactory.openSession();
Transaction tranction = session.beginTransaction();
try {
Query query = session
.createQuery("from UserDetail where user_username = :username");
query.setParameter("username", username);
List<UserDetail> userdetaillist = query.list();
UserDetail userdetail = userdetaillist.get(0);
query = session
.createQuery("from ProductDetail where product_detail_id in(:list)");
query.setParameterList("list", list);
List<ProductDetail> productdetail = query.list();
Order order = new Order();
order.setOrder_id(ordernumber);
order.setDate(date);
order.setU_id(userdetail);
order.setTotalbill(totalbill);
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = new OrderDetail();
for (ProductDetail pro : productdetail) {
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
System.out.print("totalbill" + totalbill);
System.out.println(orderdetail);
order.setOrderdetail(orderdetail);
session.save(order);
tranction.commit();
return true;
} catch (Exception e) {
tranction.rollback();
e.getStackTrace();
}
return false;
}
I think ordetail has to be created inside the for.. You are modifying the same object for each productdetail. Should be like this:
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = null;
for (ProductDetail pro : productdetail) {
ordetail = new OrderDetail();
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
Hey I have recheck my pojo class and I found out the mistake I have done. I have made change and it work properly now.
I was not setting the the id for Orderdetail table. It was auto increment in database.
So it was giving me error ""
So I have made change in orderdetail iD
"#GeneratedValue(strategy=GenerationType.AUTO)" So now It is working fine cause now hibernate know that the id will get value from database.
Thanks for the help and for your time

In hibernate even though I set cascade type to ALL, but why did I still receive a foreign key violation exception when deleting?

My database has two table. One of University, another is Faculty. They are one to many relationship
package server.hibernate.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
#Entity
#Table(name = "UNIVERSITY")
public class University implements Serializable{
private Long _id;
private int _version;
private String _universityName;
private String _countryLocated;
private Set<Faculty> _faculties = new HashSet<Faculty>();
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID")
public Long getId() {
return _id;
}
public void setId(Long _id) {
this._id = _id;
}
#Version
#Column(name = "VERSION")
public int getVersion() {
return _version;
}
public void setVersion(int _version) {
this._version = _version;
}
#Column(name = "UNIVERSITY_NAME", nullable=false)
public String getUniversityName() {
return _universityName;
}
public void setUniversityName(String _universityName) {
this._universityName = _universityName;
}
#Column(name = "COUNTRY_LOCATED")
public String getCountryLocated() {
return _countryLocated;
}
public void setCountryLocated(String _countryLocated) {
this._countryLocated = _countryLocated;
}
#OneToMany(mappedBy="university", targetEntity=Faculty.class, orphanRemoval=true, fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public Set<Faculty> getFaculties() {
return _faculties;
}
public void setFaculties(Set<Faculty> faculties) {
this._faculties = faculties;
}
public String toString(){
return new String("UniversityID:"+_id
+ " UniversityName:"+_universityName
+" CountryLocated:"+_countryLocated);
}
}
This is what I have set in University class.
package server.hibernate.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
#Entity
#Table(name="FACULTY")
public class Faculty implements Serializable{
private Long _id;
private int _version;
private String _facultyName;
private String _deanName;
private University _university;
private Set<Student> _students = new HashSet<Student>();
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID")
public Long getId() {
return _id;
}
public void setId(Long id) {
this._id = id;
}
#Version
#Column(name = "VERSION")
public int getVersion() {
return _version;
}
public void setVersion(int version) {
this._version = version;
}
#Column(name="FACULTY_NAME", nullable=false)
public String getFacultyName() {
return _facultyName;
}
public void setFacultyName(String facultyName) {
this._facultyName = facultyName;
}
#Column(name="DEAN_NAME")
public String getDeanName() {
return _deanName;
}
public void setDeanName(String dean_name) {
this._deanName = dean_name;
}
#ManyToOne
#JoinColumn(name = "UNIVERSITY_ID", nullable=false)
public University getUniversity() {
return _university;
}
public void setUniversity(University university) {
this._university = university;
}
#OneToMany(mappedBy="faculty", targetEntity=Student.class, orphanRemoval=true, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public Set<Student> getStudents() {
return _students;
}
public void setStudents(Set<Student> students) {
this._students = students;
}
public String toString(){
return new String("FacultyID:"+_id
+" FacultyName:"+_facultyName
+" DeanName:"+_deanName);
}
}
This is my faculty class
But when I use sessionFactory.delete(university). I still have this exception
Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: could not delete: [server.hibernate.domain.University#1]; SQL [delete from UNIVERSITY where ID=? and VERSION=?]; constraint ["FKE9B72644368E5BBD: PUBLIC.FACULTY FOREIGN KEY(UNIVERSITY_ID) REFERENCES PUBLIC.UNIVERSITY(ID)"; SQL statement:
delete from UNIVERSITY where ID=? and VERSION=? [23503-160]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not delete: [server.hibernate.domain.University#1]
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:643)
at org.springframework.orm.hibernate3.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:793)
at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:664)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy19.removeUniversity(Unknown Source)
at main.TestHibernateMain.test(TestHibernateMain.java:73)
at main.TestHibernateMain.main(TestHibernateMain.java:22)
Caused by: org.hibernate.exception.ConstraintViolationException: could not delete: [server.hibernate.domain.University#1]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2710)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2893)
at org.hibernate.action.EntityDeleteAction.execute(EntityDeleteAction.java:97)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:189)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
... 9 more
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKE9B72644368E5BBD: PUBLIC.FACULTY FOREIGN KEY(UNIVERSITY_ID) REFERENCES PUBLIC.UNIVERSITY(ID)"; SQL statement:
delete from UNIVERSITY where ID=? and VERSION=? [23503-160]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:398)
at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:415)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:291)
at org.h2.table.Table.fireConstraints(Table.java:861)
at org.h2.table.Table.fireAfterRow(Table.java:878)
at org.h2.command.dml.Delete.update(Delete.java:98)
at org.h2.command.CommandContainer.update(CommandContainer.java:73)
at org.h2.command.Command.executeUpdate(Command.java:219)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:143)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:129)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2692)
... 20 more
Can anyone suggest a solution?
Thanks!
I solved my problem by myself.
It is a fetch problem.
When I try remove University by using sessionFactory.delete(university), this university does not fetch any faculties. So the removal will not be cascade enabled.
This because you are trying to delete the UNIVERSITY which is associated with other faculties
thus you have to first delete associated faculties before deleting the university.

ManyToMany relation with jointable

Category EJB
package session;
import com.Entity.Category;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Item EJB
package session;
import com.Entity.Item;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class saveItemBean implements saveItemRemote {
#PersistenceContext
private EntityManager em;
public void saveItem(Item itm) {
em.persist(itm);
}
public void persist(Object object) {
em.persist(object);
}
}
Servlet for save Item
package src;
import com.Entity.Item;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import session.CategoryFacadeRemote;
import session.saveItemRemote;
public class saveItemAndIemCategory extends HttpServlet {
#EJB
private saveItemRemote saveItemBean;
#EJB
private CategoryFacadeRemote categoryFacadeBean;
processRequest(HttpServletRequest request, HttpServletResponse response) {
try {
Item itm = new Item();
itm.setName("HelloNew");
saveItemBean.saveItem(itm);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Item Entity Bean
package com.Entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
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.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#Entity
#Table(name = "item")
#NamedQueries({#NamedQuery(name = "Item.findAll", query = "SELECT i FROM Item i"), #NamedQuery(name = "Item.findByItemId", query = "SELECT i FROM Item i WHERE i.itemId = :itemId"), #NamedQuery(name = "Item.findByName", query = "SELECT i FROM Item i WHERE i.name = :name")})
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "item_id")
private Integer itemId;
#Basic(optional = false)
#Column(name = "name")
private String name;
#ManyToMany
#JoinTable(name = "item_cat",
joinColumns = {#JoinColumn(name = "item_id", referencedColumnName = "item_id")},
inverseJoinColumns = {#JoinColumn(name = "cat_id", referencedColumnName = "cat_id")})
private List<Category> categoryCollection;
public Item() {
}
public Item(Integer itemId) {
this.itemId = itemId;
}
public Item(Integer itemId, String name) {
this.itemId = itemId;
this.name = name;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Category> getCategoryCollection() {
return categoryCollection;
}
public void setCategoryCollection(List<Category> categoryCollection) {
this.categoryCollection = categoryCollection;
}
}
I am trying to persist data using these coding but only Category and Item tables are getting field (Category coding are missing here those are fine) my assosiative table item_cat is not getting saving data.
If you have an intermediate join table, you need to use the #JoinTable annotation:
#JoinTable(name="item_cat", joinColumns={ #JoinColumn(name="item_id") }, inverseJoinColumns={ #JoinColumn(name="category_id") })
Make sure you are setting the entities in both sides before persisting them. Something like this:
Item itm = new Item();
itm.setName("NewItem");
Category cat = new Category();
cat.setName("NewCategory");
itm.getCategoryCollection().add(cat);
cat.getItemCollection().add(itm);
It would be very helpful if you post you Category model.

Categories

Resources