gpt4 book ai didi

java - JPA 级联更新/删除 OneToMany

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:46 25 4
gpt4 key购买 nike

我有两个实体“文章”和“评论”。 Article 与 Comment 具有 OneToMany 关系。

@Entity
@Table(name = "article")
public class Article implements Serializable
{
public Article()
{

}
private static final long serialVersionUID = 1L;
@Id
@Column(name = "article_id")
private int articleId;
@Column(name = "title")
private String title;
@Column(name = "category")
private String category;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "articleId", cascade = CascadeType.ALL)
private List<Comment> comments = new ArrayList<>();
}


@Entity
@Table(name = "comment")
public class Comment
{
private static final long serialVersionUID = 1L;
public Comment()
{

}
@Id
@Column(name = "comment_id")
private int commentId;
@Column(name = "author")
private String author;
@Column(name = "text")
private String text;

@JoinColumn(name = "article_id", nullable = false)
private int articleId;
}

我正在使用 JPA EntityManager 对文章执行 CRUD 操作。

我在“文章”表中有一篇文章,其中包含以下数据。

article_id         title        category 

1 Java 8 in 30 days Java

我在“评论”表中有两条评论,数据如下。

comment_id   author    text              article_id

1 ABC Java is awesome ! 1
2 XYZ Nice Article !!! 1

这是我的 EntityManager 代码,当包含评论的文章有更新时,它会被调用。

public Article update(Article article)
{
return entityManager.merge(article);
}

我在这里面临的问题是,每当我使用上述方法调用从现有文章中删除评论时,评论实际上并没有从表中删除。我知道“合并”与“更新插入”相同,但我没有在 EntityManager 界面中找到任何其他方法来实现评论删除以及对文章的其他更改。

最佳答案

在您的代码中,@OneToMany(... cascade = CascadeType.ALL) 意味着无论何时对父级进行修改(保留、删除等),它都会级联到 children 也是如此。因此,如果一个 Article 被保存,其所有对应的 Comments 也会被保存。或者,如果一个 Article 被删除,其所有相应的 Comments 也被删除。

在你的例子中,你想要的只是删除一个 Comment,与其 Article 中发生的操作无关。

一个简单的方法是使用 @OneToMany(... cascade = CascadeType.ALL, orphanRemoval = true) 然后当你决定触发 delete例如,第一个 Comment,只需在其上使用 Collection.remove():

Article article = ...;
//...
Comment targetComment = article.getComments().iterator().next();
article.getComments().remove(targetComment);
// now Hibernate considers `targetComment` as orphan and it executes an SQL DELETE for it

确保您的集合是唯一持有对 targetComment 引用的对象的引用的集合,否则您将在内存中出现不一致。

关于java - JPA 级联更新/删除 OneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47091366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com