How to cascade a collection deletion in Hibernate?

Let's say I have two objects: Post and Comment (in ColdFusion):

 component persistent="true" table="post" { property name="Id" fieldtype="id"; property name="Comments" fieldtype="one-to-many" cfc="Comment" fkcolumn="post_id" cascade="all"; } component persistent="true" table="comment" { property name="Id" fieldtype="id"; property name="Post" fieldtype="many-to-one" cfc="Post" column="post_id"; } 

Post has a set of Comments . Now I would like to delete Post and automatically delete Comments . I tried a simple method:

 var post = EntityLoadByPK("Post", 13); EntityDelete(post); 

But I get a Hibernate error stating that post_id cannot be set to null. What am I doing wrong and how can I fix this problem?

+4
source share
2 answers

You need to customize your mappings. Try to make the Post property of the comment invalid and mark the property of the Post post comments as the opposite.

 component persistent="true" table="post" { property name="Id" fieldtype="id"; property name="Comments" fieldtype="one-to-many" cfc="Comment" fkcolumn="post_id" cascade="all" inverse="true"; } component persistent="true" table="comment" { property name="Id" fieldtype="id"; property name="Post" fieldtype="many-to-one" cfc="Post" column="post_id" notnull="true"; } 
+2
source

You will need to make post_id in the comments table null in your database. The way hibernate performs cascading deletion. It will set all comments with post_id = 13 as null and then delete all comments where post_id IS NULL

+1
source

All Articles