Reputation: 8067
I am using HIbernate 3.2.5. I have a one-to-many association between Dept and Training table. One dept is capable of taking more than one training.
<id name="deptId" type="integer" column="DEPT_ID">
<generator class="assigned"></generator>
</id>
<property name="deptName">
<column name="DEPT_NAME"></column>
</property>
<map name="trainingDetails" inverse="false" cascade="delete" lazy="false">
<key column="DEPT_ID"></key>
<map-key formula="ID" type="integer"></map-key>
<one-to-many class="model.Training"/>
</map>
When I try to delete an entry:
SessionFactory sf = new Configuration().configure("trial.cfg.xml").buildSessionFactory();
Session session = sf.openSession();
Dept department = new Dept();
department.setDeptId(2);
session.delete(department);
session.flush();
session.close();
I can see that for the child table an update query is getting printed in the console rather than a delete query:
update training set DEPT_ID=null where DEPT_ID=?
But since the cascade is delete
hence the child table should also execute a delete
operation rather than an update
right?
Please let me know where is my mistake.
Regards,
Upvotes: 0
Views: 55
Reputation: 34367
It will do if you use cascade as DELETE_ORPHAN
stating that child object can't exist standalone.
In addition, you are not loading the object graph before deleting. Perform delete as below:
SessionFactory sf = new Configuration().configure("trial.cfg.xml")
.buildSessionFactory();
Session session = sf.openSession();
//load the object before deleting
Dept department = session.get(Dept.class, new Integer(2));
session.delete(department);
session.flush();
session.close();
Upvotes: 1