hibernate 一对多(one to many)级联删除

我这里说的是一对多单向级联删除,其他需要级联的相应修改cascade即可

 

以Order和Item为例

1 bean 类

public class Order implements java.io.Serializable {

 

private Set items = new HashSet(0);

 

相应的get,set方法

}

 

public class Item implements java.io.Serializable {

 

private Order order; 

相应的get,set方法

}

 

2 配置文件

 

<set name="items" lazy="true" inverse="true" cascade="delete">
           <key>
                <column name="ORDERID" length="20" not-null="true" />
            </key>
           <one-to-many class="Item"/>
  </set>

 

 

       <many-to-one name="order" class="Order" cascade="none">
            <column name="ORDERID" length="20" not-null="true" />
        </many-to-one>

 

3 service保存

//级联删除item表里的相关数据

 

public void deleteOrder(String orderid){
  Order order= (Order)this.getEntity(orderid);
  Session session=this.getDao().getSessionFactory().openSession();
  session.load(order, orderid);
  session.delete(order);
  session.flush();
 }

 

这样就可以级联删除了,以前做过放在同一个事务中也可以级联删除,但是直接用dao.delete(obj)就会报错


org.springframework.orm.hibernate3.HibernateSystemException: Illegal attempt to associate a collection with two open sessions; nested exception is org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

 

希望有所帮助,我也是调了好长时间

 

你可能感兴趣的:(spring,Hibernate,bean,配置管理,Appfuse)