Requirement is when parent is deleted all related child must be deleted .I am facing problem on deletion of child when parent is deleted using hibernate annotation my parent table is Employee
and child table is EmployeeProject
child table has a foreign key constraint of Employee_Number
in database ,problem is when i delete the parent following error is coming please tell me where is the problem in mapping thanks
Hibernate: select employee_.EMPLOYEE_NUMBER, employee_.ADDRESS_1 as ADDRESS2_0_, employee_.ADDRESS_2 as ADDRESS3_0_, employee_.CITY as CITY0_, employee_.DATE_OF_ANNIVERSARY as DATE5_0_, employee_.DATE_OF_BIRTH as DATE6_0_, employee_.DATE_OF_JOINING as DATE7_0_, employee_.DATE_OF_LEAVING as DATE8_0_, employee_.DEPARTMENT_ID as DEPARTMENT9_0_, employee_.FIRST_NAME as FIRST10_0_, employee_.LAST_NAME as LAST11_0_, employee_.MOBILE_NUMBER as MOBILE12_0_, employee_.pincode as pincode0_, employee_.REASON_FOR_LEAVING as REASON14_0_, employee_.state as state0_, employee_.TELEPHONE_NUMBER as TELEPHONE16_0_, employee_.TITLE as TITLE0_ from Employees employee_ where employee_.EMPLOYEE_NUMBER=?
Hibernate: delete from Employees where EMPLOYEE_NUMBER=?
4 Mar, 2013 12:33:32 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1451, SQLState: 23000
4 Mar, 2013 12:33:32 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot delete or update a parent row: a foreign key constraint fails (`employee/employee_project`, CONSTRAINT `FKC1804A88229473A9` FOREIGN KEY (`EMPLOYEE_NUMBER`) REFERENCES `employees` (`EMPLOYEE_NUMBER`))
This is my parent mapping
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
Collection<EmployeeProject> employeeProjects = new ArrayList<EmployeeProject>();
This is child table mapping
@ManyToOne
@JoinColumn(name = "EMPLOYEE_NUMBER", insertable = false, updatable = false)
Employee employee;
this is method through which parent (employee) is deleted
@Override
public boolean deleteEmployee(Employee employee) {
Transaction transaction = null;
boolean flag;
try {
transaction = session.beginTransaction();
session.delete(employee);
transaction.commit();
flag = true;
} catch (HibernateException exception) {
if (transaction != null)
transaction.rollback();
flag = false;
}
return flag;
}
Make sure that you also have the foreign key relation marked to CASCADE
in the database schema, assuming this is what you want. Hibernate's cascade will take care of deleting Hibernate objects, but it won't, by itself, make the DELETE
kill child records that haven't been turned into objects into your application.