Hi
I've got a problem with deleting parent/child record from database, the problem is that hibernate generates
delete for parent before deleting his child and database complains
Code:
ERROR: update or delete on table "customer" violates foreign key constraint "customer_id_fk" on table "orders"
Detail: Key (cus_id)=(1) is still referenced from table "orders".
ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
the relation is configured
Customer.hbm.xml
Code:
<set name="orderses" inverse="true" table="orders" fetch="select" cascade="all,delete-orphan">
<key on-delete="cascade">
<column name="cus_id" />
</key>
<one-to-many class="Orders" />
</set>
Orders.hbm.xml
Code:
<many-to-one name="customer" class="Customer" fetch="select">
<column name="cus_id" not-null="true" />
</many-to-one>
Service for deleting customer, where i load customer that i want to delete
Code:
public void deleteCascade(){
try{
CustomerHome cusDao = new CustomerHome();
CustomerHome.getSession().beginTransaction();
Customer cus = (Customer)CustomerHome.getSession().load(Customer.class,Integer.valueOf("1"));
cusDao.delete(cus);
CustomerHome.getSession().getTransaction().commit();
CustomerHome.getSession().close();
}catch(Exception ex){
System.out.println("Error1578: "+ ex.getMessage());
}
}
Hibernate generate one delete for removing the customer, and that is the part that i am confused about.
Code:
Hibernate: delete from testo.customer where cus_id=?
in order to remove customer hibernate must delete his orders first.
What is wrong with configuration? and does lazy loading (in my case is true) has to do any thing with it?
if yes please help guys, thanks .