【问题标题】:JPA CascadeType.ALL is not deleting children orphan recordsJPA CascadeType.ALL 不会删除子孤儿记录
【发布时间】:2017-06-20 19:15:21
【问题描述】:

我正在使用带有 Hibernate 的 Spring Boot(最新版本 1.5.4)进行一个宠物项目,遇到了一个我自己无法解决的问题。

我正在尝试在帖子和评论之间创建 OneToMany 关系。

父类:

    @NotNull
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "parentPost") 
private Set<Comment> commentList;

儿童班:

    @ManyToOne
    @JoinColumn(name="parent_id")
    @JsonBackReference
    private Post parentPost;    

由于某种原因,CascadeType.ALL 不会在 DELETE 上进行级联,也不会删除孤立的评论记录。但是,如果我将 CascadeType.ALL 更改为 CascadeType.REMOVE,一切都会正常工作,并且当父 Post 被删除时,这些记录也会被删除。

有谁知道我为什么会出现这种行为?这是我的代码中的错误还是错误?

【问题讨论】:

    标签: spring hibernate jpa


    【解决方案1】:

    可能是语句顺序错误。

    假设:

    // find a post and manage it
    Post managedPost = em.find(postId); 
    
    // get a random comment - the first one
    Comment comment = managedPost.getCommentList().iterator().next();
    
    // unlink the comment from the post
    managedPost.getCommentList().remove(comment);
    
    // remove the comment from the db
    em.remove(comment);
    
    // do other things
    ....
    
    // do an useless merge on a already managed post
    em.merge(managedPost);
    

    提供者会缓存语句(只是一个概念,不要当真):

    1. select post ...em.find(postId)
    2. delete from comment ...managedPost.getCommentList().remove(comment)
    3. em.remove(comment) 的另一个 delete from comment ...(被忽略为重复)
    4. update post ...update comment ... 最后一个 em.merge(managedPost)(级联到 cmets)

    因此,最后一条语句将重新插入已删除的评论。

    您必须确保在删除或删除级联之后em.flush()

    【讨论】:

      猜你喜欢
      • 2010-09-23
      • 2011-08-31
      • 2014-10-07
      • 2013-10-29
      • 2013-06-05
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多