Sunday, December 6, 2009

Hibernate: Deleting element from a Collection doesn't get deleted in database

In Hibernate we are able to remove an element from a java.util.Collection by invoking Iterator.remove() on the Iterator object. When the collection is saved, Hibernate will automatically delete the element that was removed from the database. Below is an example of removing the element from the Collection:

            for (Iterator<StoragePosition> it = mouse.getPositions().iterator(); it.hasNext() ;) {
                StoragePosition sp =;
                if (! Util.isValid(sp.getPosition())) {        

The "cascade" attribute configured in the Hibernate configuration file (hbm.xml) plays an important role in how it will behave when handling elements that have been removed from a Collection. In order for this to work the cascade attribute should have the following value: all-delete-orphan. A cascade value of save-update will not work. Below is a segment of the configuration file:

    <set name="positions" inverse="true" table="mouse_storage_positions" cascade="all-delete-orphan" lazy="true" batch-size="8">
             <key column="mouse_id" />                      
             <one-to-many class="" />     

No comments:

Post a Comment