delete的级联操作,以及不设置级联操作的问题

<?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>
	<class name="com.zjlolife.netstore.domain.Order" table="t_order">
		<id name="id" column="order_id">
			<generator class="increment" />
		</id>
		<property name="orderNum" column="order_num" />

        <many-to-one name="customer" column="customer_id" class="com.zjlolife.netstore.domain.Customer" cascade="save-update"/>
        
	</class>
</hibernate-mapping>

<?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>
	<class name="com.zjlolife.netstore.domain.Customer" table="t_customer">
	    <id name="id" column="customer_id">
	         <generator class="increment"/>
	    </id>
	    <property name="name" column="name"/>
	   
	    <set name="orders">
	       <key column="customer_id"/>
	       <one-to-many class="com.zjlolife.netstore.domain.Order"/>
	    </set>
	</class>
</hibernate-mapping>


测试Test.java

public void test3() {
		Session session = HibernateUtil.getInstance().getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		try {
			Customer customer = (Customer)session.get(Customer.class, 1);
			session.delete(customer);
			tx.commit();
		}catch(Exception e) {
			tx.rollback();
			e.printStackTrace();
		}finally {
			session.close();
		}
	}


customer与order是一对多的双向关系,下面删除的问题就来了

只在customer中的set配置(修改xml):

①什么也不修改,结果为,Update order  null  和  delete customer

②lazy="false  结果为报错:org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): [com.zjlolife.netstore.domain.Customer#1]

因为lazy="false"的时候,get上来的customer,中的set<Order> orders不为空,而删除customer的时候,必须先清楚customer,和oder之间的关系。所以会报错。

当lazy="true" 的时候,get上来的customer中的orders为空,相当于清楚了关系,因此可以删除customer

③lazy="true",inverse="true",此时会报错,外键约束错误

④lazy="false",inverse="true",必然报错,不用想了


⑤cascade="all",不会报错,但会先发出update外键为Null,再发出2条delete语句删除order与customer

在这种情况,我发现了很特别的情况,当delete(customer)的时候会发出select order语句,我觉得是因为在级联的情况下,会在delete()的时候加载order。

因为customer控制了关系,所以删除之前会先update  order null

⑥cacade="all",inverse="true" ,在这种情况下:

Hibernate: delete from t_order where order_id=?
Hibernate: delete from t_customer where customer_id=?只发出两条delete



展开阅读全文

没有更多推荐了,返回首页