码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate:deleted object would be re-saved by cascade (remove deleted object from associations): []

时间:2016-05-07 08:36:48      阅读:461      评论:0      收藏:0      [点我收藏+]

标签:

Hibernate多表关联的时候的异常:deleted object would be re-saved by cascade (remove deleted object from associations): []。
【产生原因】表之间的一对多(多对一)关联,两种情况:双表一对多多对一,单表自关联一对多多对一。表现为:删除“多”的一方的条目的时候出现这个异常。
【具体环境背景】楼主是在单表自关联(双向一对多多对一)出现的,建表细节:

@Entity
public class Department {

    private Long id;
    private Set<User> users = new HashSet<User>();
    private Department parent;
    private Set<Department> children = new HashSet<Department>();
    private String name;
    private String description;

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    @ManyToOne(cascade=CascadeType.MERGE)
    @JoinColumn(name="parent_id")
    public Department getParent() {
        return parent;
    }

    public void setParent(Department parent) {
        this.parent = parent;
    }

    @OneToMany(mappedBy="parent",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
    public Set<Department> getChildren() {
        return children;
    }

    public void setChildren(Set<Department> children) {
        this.children = children;
    }
}

可见是Department部门表的自关联,每个部门都有一个上级部门和一个下级部门。我们理想状态的删除是:删除一个部门,1、它所有的下级部门级联删除,2、所有的上级部门不发生任何变化。
【解决方法!!!】由异常信息得知:deleted object would be re-saved by cascade (remove deleted object from associations)—->删除掉的对象将会被级联第二次保存(从绑定的联系上移除已经被删除的对象)。这说明我们已经做到了删除但是却由于级联(cascade)的原因,删除的对象又被利用了等等……,所以要做的是解决办法是:把@OneToMany里的cascade=CascadeType.ALL改成cascade=CascadeType.REMOVE。其他无关。
**【总结】**1、善于阅读思考异常内容。
2、cascade=CascadeType.ALL慎用,无论是在Many的一方还是One的一方。
3、当然,扎实基础是关键。

Hibernate:deleted object would be re-saved by cascade (remove deleted object from associations): []

标签:

原文地址:http://blog.csdn.net/sinat_23179379/article/details/51330183

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!