十二、级联cascade
1.
级联操作用来说明当主对象进行某种操作时是否对其关联的从对象也作类似的操作,常用的cascade有none,all,save-update,delete,lock,refresh,evict,replicate,persist,merge,delete-orphan(one-to-many).一般对many-to-one,many-to-many不设置级联,在<one-to-many>和<one-to-one>中设置级联。
2.
如在one2many案例中,Department.hbm.xml中添加级联
<!-- cascade="delete" 当删除该部门的时候(主对象),则级联删除该部门的学生(从对象)--> <set name="emps" cascade="delete"> <key column="dep_id"></key> <one-to-many class="Employee"/> </set>
//删除该部门的时候,自动删除部门内的员工 public static void main(String[] args) { // TODO Auto-generated method stub Session s=null; Transaction tx=null; try { s=HibernateUtil.getCurrentSession(); tx=s.beginTransaction(); Department department=(Department) s.get(Department.class, 1); s.delete(department); tx.commit(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); if(tx!=null){ tx.rollback(); } }finally{ if(s!=null&&s.isOpen()){ s.close(); } } }
<!-- cascade="save-update" 当保存该部门的时候(主对象),则级联保存该部门的学生(从对象)--> <set name="emps" cascade="save-update"> <key column="dep_id"></key> <one-to-many class="Employee"/> </set>
public static void main(String[] args) { // TODO Auto-generated method stub Session s=null; Transaction tx=null; try { s=HibernateUtil.getCurrentSession(); tx=s.beginTransaction(); Department department=new Department(); department.setName("管理部"); department.setId(3); Employee e=new Employee(); e.setName("小强"); e.setId(3); Set<Employee> emps=new HashSet<Employee>(); emps.add(e); //此时department知道了它有哪些员工,所以保存department即级联保存了该部门的学生 department.setEmps(emps); s.save(department); tx.commit(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); if(tx!=null){ tx.rollback(); } }finally{ if(s!=null&&s.isOpen()){ s.close(); } } }