简体   繁体   English

如何在Hibernate中级联删除集合?

[英]How do I cascade delete a collection in Hibernate?

Let's say I have two entities, a Post and a Comment (in ColdFusion): 假设我有两个实体,一个Post和一个Comment (在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 collection of Comments . Post有一系列Comments Now I'd like to delete a Post , and have the Comments automatically deleted as well. 现在我想删除Post ,并自动删除Comments I've tried the straightforward method: 我尝试了直截了当的方法:

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

But I'm getting a Hibernate error that says that post_id cannot be set to null. 但我收到一个Hibernate错误,指出post_id不能设置为null。 What am I doing wrong, and how can I fix this issue? 我做错了什么,我该如何解决这个问题?

You need to adjust your mappings. 您需要调整映射。 Try making the Post property of comment not null and marking the Comments property of post as inverse. 尝试使注释的Post属性不为null,并将post的Comments属性标记为inverse。

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

You'll have to make post_id in Comment table nullable in your DB. 你必须在你的数据库中将注释表中的post_id设为nullable。 That's how hibernate does cascade delete. 这就是hibernate如何级联删除。 It'll set all Comments with post_id = 13 as null, then delete all comments where post_id IS NULL 它将使用post_id = 13将所有注释设置为null,然后删除post_id为NULL的所有注释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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