Introduction
I was testing cascade delete option in one-to-many association. When parent that have many children is deleted its children are also deleted.
Hibernate version:
2.1.6
Mapping documents:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="jbeans">
<class
name="C1"
table="C1"
lazy="true"
>
<id
name="ID"
type="long"
column="ID"
>
<generator class="native"/>
</id>
<many-to-one
name="c2"
column="C2_ID"
/>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="jbeans">
<class
name="C2"
table="C2"
lazy="true"
>
<id
name="ID"
type="long"
column="ID"
>
<generator class="native"/>
</id>
<bag
name="c1s"
cascade="delete"
inverse="true"
lazy="true"
>
<key
column="C2_ID"
/>
<one-to-many class="C1"/>
</bag>
</class>
</hibernate-mapping>
Code between sessionFactory.openSession() and session.close():
SessionFactory sf = conf.buildSessionFactory();
ses = sf.openSession();
tr = ses.beginTransaction();
C1 c1 = new C1();
C1 c12 = new C1();
C2 c2 = new C2();
c2.setC1s(new LinkedList());
ses.save(c1);
ses.save(c12);
ses.save(c2);
c1.setC2(c2);
c12.setC2(c2);
c2.getC1s().add(c1);
c2.getC1s().add(c12);
tr.commit();
ses.close();
ses = sf.openSession();
tr = ses.beginTransaction();
c2 = (C2)ses.get(C2.class,c2.getID());
ses.delete(c2);
tr.commit();
ses.close();
Name and version of the database you are using:
MySQL 4.0.13
The generated SQL (show_sql=true):
Hibernate: insert into C1 (C2_ID) values (?)
Hibernate: insert into C1 (C2_ID) values (?)
Hibernate: insert into C2 values ( )
Hibernate: update C1 set C2_ID=? where ID=?
Hibernate: update C1 set C2_ID=? where ID=?
Hibernate: select c20_.ID as ID0_ from C2 c20_ where c20_.ID=?
Hibernate: select c1s0_.C2_ID as C2_ID__, c1s0_.ID as ID__, c1s0_.ID as ID0_, c1s0_.C2_ID as C2_ID0_ from C1 c1s0_ where c1s0_.C2_ID=?
Hibernate: delete from C1 where ID=?
Hibernate: delete from C1 where ID=?
Hibernate: delete from C2 where ID=?
Problem
The problem is that each child is deleted in separate SQL delete statement. In SQL it is possible to do it in one statement, in this case it would be delete from C1 where C2_ID=?. Is it posibble and how can I force hibernate to do it in only one SQL statement.
_________________ Lmichasz
|