Search This Blog

Saturday 26 November 2011

cascade = "delete-orphan"

In an earlier post we have seen the various settings supported by cascade property. In a parent-child relationship we are provided with three different type of cascades:
  • save-update
  • delete
  • delete-orphan
Save-update ensures that changes to the Children will be saved when the Parent entity is updated/created by Hibernate.
If the setting is delete, it means calling session.delete(parent) should delete the parent entity and also the children in the collection. (Subject to the condition that these are in no way linked to any other rows in the database.)
Hibernate also includes a third option :- delete-orphan
Consider the scenario that a Book has been lost and hence needs to be moved out of the shelf. In this case the book record needs to be deleted from the database.The code to do the same would be
Session session = sessionFactory.openSession();
    Transaction t = session.beginTransaction();
    Book book1 = new Book();
    book1.setName("Lord Of The Rings");
    //removing an element from the set
    Shelf shelf1 = (Shelf) session.get(Shelf.class, 1);        
    shelf1.getBooks().remove(book1);
    session.delete(book1);// This will delete the Book object
    t.commit();    
    session.close();
As can be seen a delete call was necessary on that book1 object to remove it from the database. (Assuming all other links to this record have been separated)
If instead delete-orphan settings are used the same, Hibernate will delete the book once it is removed from the set of shelf entity. The change in the mapping file would be :
<set name="books" cascade="save-update,delete,delete-orphan" inverse="true">
    <key column="SHELF_ID" foreign-key="BOOK_FK_1" />
    <one-to-many class="Book" />
</set>
On executing the updated code for deletion:
Shelf shelf1 = (Shelf) session.get(Shelf.class, 1);        
shelf1.getBooks().remove(book1);
//session.delete(book1);// This is unnecessary now
t.commit();
The logs indicate that the book was removed successfully from the system:
3547 [main] DEBUG org.hibernate.persister.entity.AbstractEntityPersister  - Dele
ting entity: [com.collection.cascade_delete_orphan.Book#1]
3547 [main] DEBUG org.hibernate.jdbc.AbstractBatcher  - about to open PreparedSt
atement (open PreparedStatements: 0, globally: 0)
3547 [main] DEBUG org.hibernate.SQL  - 
    delete 
    from
        BOOK 
    where
        ID=?

No comments:

Post a Comment