简体   繁体   中英

Delete child objects/records in one-to-many relationship using Hibernate

I have a parent-child (one-to-many) relationship between product & packages. one product can have multiple packages. In my 'Edit Product' jsp page I am allowing user to edit product & delete/add/edit any package. Now, on submitting the changes I am doing saveOrUpdate(product) in my controller method. What I am observing is that new packages are getting added in DB but the ones that are deleted by user hence not in the packages Set of Product are not getting deleted from DB. My hiberate configurations snippet is below. Am I missing something here?

<hibernate-mapping>
    <class name="author.vo.ProductVO" table="Product">
    <id name="ProductID" type="long">
            <column name="Product_ID" />
            <generator class="increment" />
     </id>
    <set name="packages" inverse="true" cascade="all" lazy="false">
    <key column="Product_ID" not-null="true" on-delete="cascade"/>
    <one-to-many class="author.vo.PackageVO" />
     </set>

Code for adding product

@Autowired
private HibernateTemplate hibernateTemplate;

this.hibernateTemplate.saveOrUpdate(prod);

You should add "cascade delete orphan" to your xml config, also, why dont you try a simple situation first of all.

  1. is a save working with a parent - child.
  2. is a delete working with a parent - child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM