Hibernate - Avoid delete of all entity structure (cascade delete up)

November 12, 2015

Problem:

When issuing an delete action Hibernate cascades up and deletes all the entity structure.

_ for(ShopProductSpec shopProductSpec: shopProductSpecs) {
            shopProductSpecDAO.delete(shopProductSpec);
        }_
_        …_
_        Hibernate: delete from shop_product_brand where shop_product_id=?
        Hibernate: delete from shop_product_brand where shop_product_id=?
        Hibernate: delete from shop_product_uid where id=?
        Hibernate: delete from shop_product_image where id=?
        Hibernate: delete from shop_product_image where id=?
        Hibernate: delete from shop_product_image where id=?
        Hibernate: delete from shop_product_image where id=?
        Hibernate: delete from shop_product_image where id=?
        Hibernate: delete from shop_product_spec where id=?
        Hibernate: delete from shop_product_spec where id=?
        Hibernate: delete from shop_product_spec where id=?
        Hibernate: delete from shop_product_spec where id=?
        Hibernate: delete from shop_product_spec where id=?
        Hibernate: delete from shop_product_uid where id=?
        Hibernate: delete from shop_product_uid where id=?
        Hibernate: delete from shop_product_uid where id=?
        …_
_        Hibernate: delete from shop_product_uid where id=?
        Hibernate: delete from shop_product_uid where id=?
        Hibernate: delete from shop_product where id=?_

Solution:

We can solve this by issuing the delete on an empty object containing solely the id we want to delete:

_**       ShopProductSpec shopProductSpec = null;**
        for(ShopProductSpec ishopProductSpec: shopProductSpecs) {
**          shopProductSpec = new ShopProductSpec();
          shopProductSpec.setId(ishopProductSpec.getId());**
            shopProductSpecDAO.delete(shopProductSpec);
        }_