class="java" name="code"> Session session = HibernateUtil.openSession();
Transaction tx = null;
tx = session.beginTransaction();
User user=(User) session.load(User.class, 564);
session.delete(user);
tx.commit();
session.close();
<set name="orders" cascade="save-update" inverse="true" lazy="false">
由于一个user对应多个order, 这里user还有外联记录, 所以会报错。
ERROR: ORA-02292: 违反完整约束条件 (ALLENI.FK_QCPYHSS71C9CAMNA3X8K2Q0D9) - 已找到子记录
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
解决方法是吧User.hbm.xml配置文件的set的cascade属性修改成"delete"。
再次执行程序, hibernate会自动执行两个delete语句:
Hibernate: select user0_.id as id1_2_0_, user0_.test_name as test2_2_0_, user0_.test_age as test3_2_0_ from test_user user0_ where user0_.id=?
Hibernate: select orders0_.customer_id as customer3_2_1_, orders0_.id as id1_0_1_, orders0_.id as id1_0_0_, orders0_.test_name as test2_0_0_, orders0_.customer_id as customer3_0_0_ from test_order orders0_ where orders0_.customer_id=?
Hibernate: delete from test_order where id=?
Hibernate: delete from test_user where id=?
=============================
cascade可以有多种属性值, 如下图所示:
这里我们可以把属性值改成all, 这样一来, 不论是加入数据, 更新,还是删除, hibernate都会帮我们进行自动处理。
- 大小: 135.7 KB