Hibernate入门(九)级联删除
Hibernate级联删除
上一篇文章学习了级联保存和更新,这个级联删除应该很好理解的。一样的道理,删除一方,同时删除有关联的一方。
https://www.cnblogs.com/deepSleeping/p/9978296.html
同样有方向性。
删除客户,客户下的订单也同样删除。
用户表:
订单表:
业务:删除id值为1的客户,想要的效果:同时删除id值为1的客户下的所有订单
1.配置customer.hbm.xml文件(cascade = "delete")
<!-- 配置一对多属性 --> <set name="ods" cascade="delete"> <key column="cust_order_id" ></key> <one-to-many class="Order"/> </set>
2.java测试类
/**
* 删除id值为1的用户,级联删除该用户下的订单
*/
@Test
public void fun(){
Session session = HibernateUtils.getSession();
session.getTransaction().begin();
try {
//获取id值为1的用户 持久态
Customer cst = session.get(Customer.class, 1);
session.delete(cst);
} catch (Exception e) {
session.getTransaction().rollback();
// TODO Auto-generated catch block
e.printStackTrace();
}
session.getTransaction().commit();
}
生成的SQL语句
Hibernate: select customer0_.cust_id as cust_id1_0_0_, customer0_.cust_name as cust_nam2_0_0_, customer0_.cust_gender as cust_gen3_0_0_, customer0_.cust_age as cust_age4_0_0_, customer0_.cust_phone as cust_pho5_0_0_ from customera customer0_ where customer0_.cust_id=? Hibernate: select ods0_.cust_order_id as cust_ord3_1_0_, ods0_.order_id as order_id1_1_0_, ods0_.order_id as order_id1_1_1_, ods0_.detail_id as detail_i2_1_1_, ods0_.cust_order_id as cust_ord3_1_1_ from ordersa ods0_ where ods0_.cust_order_id=? Hibernate: update ordersa set cust_order_id=null where cust_order_id=? Hibernate: delete from ordersa where order_id=? Hibernate: delete from ordersa where order_id=? Hibernate: delete from customera where cust_id=?
很明显,删除了id为1的客户同时,删除了该客户下的订单
然后翻转方向,删除订单,同时删除有这个订单的所有客户(虽然应该不会有这种奇怪的需求把....hah )
一样的配置和java代码编写后同样是测试成功了。
提示:最好在测试第二个之前,要把customer.hbm.xml配置中的级联删除的属性去掉,不然订单删除,然后删除级联的客户,客户删除后,又级联删除该客户下的订单,如此反复,估计表里的数据也差不多没了吧。。。。