Hibernate---inverse,cascade(4)

删除分支机构:

测试代码如下:

session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
BranchInfo branchInfo = (BranchInfo) session.load(BranchInfo.class, Long.valueOf(1));
session.delete(branchInfo);
System.out.println("success_____________");
tx.commit();
设置inverse=true cascade=save-update发出sql语句如下:

Hibernate: delete from tbranchinfo where id=?

但是报出异常:
org.hibernate.exception.ConstraintViolationException: could not delete:

Caused by: java.sql.SQLException: Cannot delete or update a parent row: a foreign key constraint fails

不能删除,违反了约束型异常,其实是hibernate捕获了数据库异常,然后自己封装而成。

设置inverse=true cascade=delete发出sql语句如下:

Hibernate: update tsealmodel set sealId=null where sealId=?
Hibernate: delete from tseal where id=?
Hibernate: delete from tbranchinfo where id=?

可以发现inverse对删除不起作用,主要看cascade如果为delete那么将级联删除set集合

删除印章:

设置cascade=save-update测试代码如下:

session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Seal seal = (Seal) session.load(Seal.class, Long.valueOf(1));
session.delete(seal);
System.out.println("success_____________");
tx.commit();

发出sql语句如下:

Hibernate: delete from tsealmodel where id=?
Hibernate: delete from tseal where id=?

说明:

删除与inverse无关,如果cascade=delete那么将级联删除。

你可能感兴趣的:(Hibernate)