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

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);
        }

Comments

Popular posts from this blog

Hibernate - HibernateException: createQuery is not valid without active transaction