如何在 Hibernate 中级联删除集合?
假设我有两个实体,一个 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
有一个 Comments
集合>。现在我想删除帖子
,并自动删除评论
。我尝试了简单的方法:
var post = EntityLoadByPK("Post", 13);
EntityDelete(post);
但我收到一个 Hibernate 错误,指出 post_id
不能设置为 null。我做错了什么,如何解决这个问题?
Let's say I have two entities, a Post
and a 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 collection of Comments
. Now I'd like to delete a Post
, and have the Comments
automatically deleted as well. 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. What am I doing wrong, and how can I fix this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要调整您的映射。尝试将 comment 的 Post 属性设置为不为 null,并将 post 的 Comments 属性标记为 inverse。
You need to adjust your mappings. Try making the Post property of comment not null and marking the Comments property of post as inverse.
您必须使数据库中 Comment 表中的 post_id 可为空。这就是hibernate进行级联删除的方式。它将把 post_id = 13 的所有评论设置为 null,然后删除 post_id IS NULL 的所有评论
You'll have to make post_id in Comment table nullable in your DB. That's how hibernate does cascade delete. It'll set all Comments with post_id = 13 as null, then delete all comments where post_id IS NULL