Hibernate 级联添加删除
问题描述:实体类答案从属于实体类问题。(一对多) /** * 添加 问题 和 选项 * @throws Exception */@Test public void testQu() throws Exception { Session session = HibernateUtil.currentSession(); Transaction tr = session.beginTransaction(); //级联添加 Set options = new HashSet(); Options op1 = new Options(); op1.setName("op1"); options.add(op1); Options op2 = new Options(); op2.setName("op2"); options.add(op2); Options op3 = new Options(); op3.setName("op3"); options.add(op3); Problems problems = new Problems(); problems.setName("problem_1"); problems.setOptions(options); problems.setTdesc("tdesc"); problems.setType(1); Long ll = (Long)session.save(problems); System.out.println(ll); tr.commit(); mysql> select * from options ; +----+------------+--------+------+---------+ | id | problemsid | answer | name | visible | +----+------------+--------+------+---------+ | 1 | 1 | NULL | op2 | 0 | | 2 | 1 | NULL | op3 | 0 | | 3 | 1 | NULL | op1 | 0 | +----+------------+--------+------+---------+ 3 rows in set (0.00 sec) mysql> select * from problems ; +----+-----------+------+-------+------------+---------+ | id | name | type | tdesc | questionid | visible | +----+-----------+------+-------+------------+---------+ | 1 | problem_1 | 1 | tdesc | NULL | 0 | +----+-----------+------+-------+------------+---------+ 1 row in set (0.00 sec) //级联删除 tr.begin(); session.delete( session.get(Problems.class,ll) ); tr.commit(); mysql> select * from problems ; Empty set (0.00 sec) mysql> select * from options ; Empty set (0.00 sec) HibernateUtil.closeSession(); } Options类 ....... /** * @hibernate.many-to-one * cascade = "save-update" * column = "Problemsid" * class = "com.zhongqi.domain.Problems" * @return */ public Problems getProblems() { return problems; } ............ Problems 类 /** * @hibernate.set * cascade="all-delete-orphan" * inverse = "false" * lazy = "true" * @hibernate.collection-key column = "problemsid" * @hibernate.collection-one-to-many class = "com.zhongqi.domain.Options" * @return */ public Set getOptions() { return options; }