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

发布于 2024-12-06 05:13:13 字数 735 浏览 0 评论 0原文

假设我有两个实体,一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我一直都在从未离去 2024-12-13 05:13:13

您需要调整您的映射。尝试将 comment 的 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 need to adjust your mappings. Try making the Post property of comment not null and marking the Comments property of post as 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";
}
赠我空喜 2024-12-13 05:13:13

您必须使数据库中 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文