This is a mirror of official site: http://jasper-net.blogspot.com/

That pesky Hibernate

| Wednesday, February 9, 2011
Yesterday a collegue of mine asked if I could build some functionality to physically delete records in our database.  Since deleting things is always a good idea, I immediately started to work on his request. As we are using an ORM (Hibernate) to manage our relational persistence, this would just be a matter of adding a single line of code:

session.delete(someEntity);

And all the Hibernate magic combined with some cascading would take care of the deletion. So I concluded my assignment fast, and got the well know warm cosy feeling: 'job wel done'.
However, suddenly I realised that the combinaton: "hibernate, magic, job well done, warm cosy feeling" has put me into problems before. In fact, I remeber this since last time I was in that position I ended up feeling exactly like this man did.

Just to be sure I went back to the code and configured my logging to print out what Hibernate was doing. As it turned out, something bad was going on. It seems that also Hibernate has difficulties deleting relationships (thats a line to think about).

The problem is that each child is deleted one by one.

Lets say you have two entities: Person and Product. There is a one to many relationship between Person and Product.
The relationship is uni-directional from Person to Product, mapped as a Set, managed by Person (as there is only one side) and the cascading is set to all-delete-orphan.

<hibernate-mapping default-access="field" >
  <class name="entities.Person" table="person">
     <id name="id" column="id" access="property">
        <generator class="native"/>
     </id>

     <set name="products" cascade="all-delete-orphan">
        <key column="person_id" not-null="true" update="false" foreign-key="person_fk"/>
        <one-to-many class="entities.Product"/>
     </set>
  </class>
</hibernate-mapping>

<hibernate-mapping default-access="field" >
  <class name="entities.Product" table="product">
 
     <id name="id" column="id" access="property">
        <generator class="native"/>
     </id>
     
     <property name="name" column="name"/>
  </class>
</hibernate-mapping>

If you delete a Person object which has 5 products, you will see that pesky Hibernate doing this:

31398 [main] DEBUG org.hibernate.SQL  - delete from product where id=?
31399 [main] DEBUG org.hibernate.SQL  - delete from product where id=?
31399 [main] DEBUG org.hibernate.SQL  - delete from product where id=?

Read more: Warp 10 Mr. Crusher. Engage!

Posted via email from Jasper-net

0 comments: