这个问题个人认为看你用的那种方式,如果是注解式的

比如:

@ManyToMany(cascade={CascadeType.MERGE,CascadeType.REFRESH,CascadeType.PERSIST}, fetch = FetchType.LAZY)

@JoinTable(name = "F_USERTOAUTHORITY", joinColumns = { @JoinColumn(name = "authorityid") }, inverseJoinColumns = { @JoinColumn(name = "userid") })

private List<User> users;

CascadeType不要写成all就可以解决了!

deleted object ould be re-saved by cascade

在Hibernate中,删除存在关联关系的一个对象时,会出现 org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)这个异常

如下:
持久化类:

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * 产品类别对象
 * @author crazycy
 *
 */
public class ProductCategory extends BaseObject {

// Fields

private long id;

private String name;

private String description;

private ProductCategory parentCategory;

private Set childrenCategories = new HashSet();

// Constructors

/** default constructor */
    public ProductCategory() {
    }

/** minimal constructor */
    public ProductCategory(String name) {
        this.name = name;
    }
    
    public ProductCategory(String name, String description) {
        this.name = name;
        this.description = description;
    }

/** full constructor */
    public ProductCategory(String name, String description,
            ProductCategory parentCategory) {
        this.name = name;
        this.description = description;
        this.parentCategory = parentCategory;
    }

/** full constructor */
    public ProductCategory(String name, String description,
            Set childrenCategories) {
        this.name = name;
        this.description = description;
        this.childrenCategories = childrenCategories;
    }

// Property accessors

public long getId() {
        return this.id;
    }

public void setId(long id) {
        this.id = id;
    }

public String getName() {
        return this.name;
    }

public void setName(String name) {
        this.name = name;
    }

public String getDescription() {
        return this.description;
    }

public void setDescription(String description) {
        this.description = description;
    }

public ProductCategory getParentCategory() {
        return this.parentCategory;
    }

public void setParentCategory(ProductCategory parentCategory) {
        this.parentCategory = parentCategory;
    }
    
    /**
     * 由主来调:是主添加
     * @param productCategory
     */
    public void addCategory(ProductCategory productCategory) {
        productCategory.setParentCategory(this);
        childrenCategories.add(productCategory);
    }
    
    /**
     * 由主来调;是从主删除
     * @param productCategory
     */
    public void removeCategory(ProductCategory productCategory) {
        childrenCategories.remove(productCategory);
        productCategory.setParentCategory(null);
    }
    
    public Set getChildrenCategories() {
        return childrenCategories;
    }

public void setChildrenCategories(Set childrenCategories) {
        this.childrenCategories = childrenCategories;
    }

/**
     * @see java.lang.Object#equals(Object)
     */
    public boolean equals(Object object) {
        if (!(object instanceof ProductCategory)) {
            return false;
        }
        ProductCategory rhs = (ProductCategory) object;
        return new EqualsBuilder().append(this.description, rhs.description)
                .append(this.name, rhs.name).append(this.id, rhs.id).isEquals();
    }

/**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return new HashCodeBuilder(1009592109, -669108101).append(
                this.description).append(this.name).append(this.id)
                .toHashCode();
    }

/**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return new ToStringBuilder(this).append("name", this.name).append(
                "description", this.description).append("id", this.id)
                .toString();
    }

}

映射文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="">
    <class name="ProductCategory" table="productcategory">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="name" type="string">
            <column name="name" length="50" not-null="true" />
        </property>
        <property name="description" type="string">
            <column name="description" length="150" />
        </property>
        <set name="childrenCategories" cascade="save-update" inverse="true">
            <key column="parent"/>
            <one-to-many class="ProductCategory"/>
        </set>
        <many-to-one name="parentCategory" column="parent" 
            class="ProductCategory" 
            cascade="save-update"
         >
        </many-to-one>
    </class>
</hibernate-mapping>

测试代码:

category2.getChildrenCategories().remove(category5);
        category5.setParentCategory(null);
        dao.removeProductCategory(category5.getId());

解决方案如下:
方法1 删除Set方的cascade
方法2 解决关联关系后,再删除 :

category2.getChildrenCategories().remove(category5);
        category5.setParentCategory(null);
        dao.removeProductCategory(category5.getId());

方法3 在many-to-one方增加cascade 但值不能是none

如果以上三个方案都失败(哼哼~ 我用了5个小时才找出来的)
检查一下hashCode equals是否使用了id作为唯一标示的选项了;我用uuid.hex时是没有问题的;
但是用了native,就不行了,怎么办?删除啊!

也就是问题出现在本文给出的持久化类的hashCode equals方法身上

hibernate注解的CascadeType属性

cascade表示级联操作

CascadeType.MERGE级联更新:若items属性修改了那么order对象保存时同时修改items里的对象。对应EntityManager的merge方法

CascadeType.PERSIST级联刷新:获取order对象里也同时也重新获取最新的items时的对象。对应EntityManager的refresh(object)方法有效。即会重新查询数据库里的最新数据

CascadeType.REFRESH级联保存:对order对象保存时也对items里的对象也会保存。对应EntityManager的presist方法

CascadeType.REMOVE级联删除:对order对象删除也对items里的对象也会删除。对应EntityManager的remove方法

CascadeType.PERSIST只有A类新增时,会级联B对象新增。若B对象在数据库存(跟新)在则抛异常(让B变为持久态)

CascadeType.MERGE指A类新增或者变化,会级联B对象(新增或者变化)

CascadeType.REMOVE只有A类删除时,会级联删除B类;

CascadeType.ALL包含所有;

CascadeType.REFRESH没用过。

综上:大多数情况用CascadeType.MERGE就能达到级联跟新又不报错,用CascadeType.ALL时要斟酌下CascadeType.REMOVE

@Fetch:

定义了加载关联关系的获取策略. FetchMode 可以是

SELECT (在需要加载关联的时候触发select操作), SUBSELECT(只对集合有效,使用了子查询策略,详情参考Hibernate参考文档)

JOIN (在加载主实体(owner entity)的时候使用SQL JOIN来加载关联关系).

JOIN 将覆写任何延迟属性 (通过 JOIN策略加载的关联将不再具有延迟性).

hibernate CasCade deleted object ould be re-saved by cascade的更多相关文章

  1. org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade 解决方案 (网络转载)

    前提是配置了cascade=all,依然报这种错误,其实出现这个错误的大多数情况根本不是像网上的帖子所说的是什么级联删除的问题,而且hibernate session关于实体生命周期操作的原因,这里明 ...

  2. 解决hibernate删除时的异常 deleted object would be re-saved by cascade (remove deleted object from associa

    今天在做项目时,需要删除一个对象,由于关联关系是一对多和多对一的关系,于是在代码中需要删除多的一方的对象时出现了 deleted object would be re-saved by cascade ...

  3. NHibernate删除数据时遇到deleted object would be re-saved by cascade级联问题

    今天在处理数据时遇到了这个问题,数据是一对多的关系,A包含多个B,想将某个B从A中移除,在保存时抛出如标题的问题,查找了下资料得知:由于在配置文件中设置了cascade为all,A和B存在级联关系,那 ...

  4. Hibernate 集合映射 一对多多对一 inverse属性 + cascade级联属性 多对多 一对一 关系映射

    1 . 集合映射 需求:购物商城,用户有多个地址. // javabean设计 // javabean设计 public class User { private int userId; privat ...

  5. Hibernate级联操作和载入机制(二) cascade and fetch

    上一篇介绍了Hibernate持久化对象时候的级联操作.本篇介绍读取时候的级联操作. 还是用上一篇的样例.一份问卷有多个问题.可是每一个问题仅仅能属于一份问卷. 我们先看測试用例: @Test pub ...

  6. Hibernate 一对一、一对多、多对多注解cascade属性的总结

    作用:是否级联被注解字段里面的对象.可选值:javax.persistence.CascadeType.PERSIST, MERGE, REMOVE, REFRESH, DETACH, ALL.可选其 ...

  7. Hibernate的数据删除,更改

    其他未给出代码,请参考上一篇.... 一.数据的删除 方法1.从“多”的一方进行数据的删除 books.hbm.xml文件不变: <many-to-one name="publishe ...

  8. spring+hibernate常见异常集合

    spring+hibernate出错小结: (1)java.lang.NoClassDefFoundError: org/hibernate/context/CurrentSessionContext ...

  9. Hibernate常见错误整理

    Hibernate常见错误合集   1.错误:object references an unsaved transient instance - save the transient instance ...

随机推荐

  1. IE 代理服务器设置程序实现

    IE 代理服务器设置程序实现 分类: Delphi2003-08-02 18:42 1398人阅读 评论(0) 收藏 举报 服务器ieinternetstringconstructordelphi 本 ...

  2. [C/C++] 虚函数机制

    转自:c++ 虚函数的实现机制:笔记 1.c++实现多态的方法 其实很多人都知道,虚函数在c++中的实现机制就是用虚表和虚指针,但是具体是怎样的呢?从more effecive c++其中一篇文章里面 ...

  3. Linux的cut命令

    cut是一个选取命令,就是将一段数据经过分析,取出我们想要的.一般来说,选取信息通常是针对“行”来进行分析的,并不是整篇信息分析的. (1)其语法格式为:cut  [-bn] [file] 或 cut ...

  4. jmeter 配置元件之计数器Counter

    用jmeter生成数据 我用过几种以下几种方法 1.CSV Data Set Config  参数化 2.${_Random} ${_Random}是jmeter函数助手里面自带的一个函数,作用是返回 ...

  5. 第145天:jQuery.touchSlider触屏满屏左右滚动幻灯片

    1.HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

  6. 【.Net】net 反射15分钟速成

    概述 什么是反射 Reflection,中文翻译为反射.        这是.Net中获取运行时类型信息的方式,.Net的应用程序由几个部分:‘程序集(Assembly)’.‘模块(Module)’. ...

  7. 【bzoj3697】采药人的路径 树的点分治

    题目描述 给出一棵 $n$ 个点的树,每条边的边权为1或0.求有多少点对 $(i,j)$ ,使得:$i$ 到 $j$ 的简单路径上存在点 $k$ (异于 $i$ 和 $j$ ),使得 $i$ 到 $k ...

  8. java利用poi读取excel异常问题

    最近一个web工程需要完成一个小功能,利用文件上传然后读取文件内容写入到数据库,这里是操作的excel文件,excel文件分两种后缀,03版本的xls和之后的xlsx,现在大家一般都拿非常好用的插件直 ...

  9. poj2299——Ultra-QuickSort

    Description In this problem, you have to analyze a particular sorting algorithm. The algorithm proce ...

  10. 【刷题】BZOJ 1468 Tree

    Description 给你一棵TREE,以及这棵树上边的距离.问有多少对点它们两者间的距离小于等于K Input N(n<=40000) 接下来n-1行边描述管道,按照题目中写的输入 接下来是 ...