hibernate---級聯保存、級聯刪除
阿新 • • 發佈:2018-09-22
cad app 也會 one comm asc update string emp
直接上菜:
dept.hbm.xml:關鍵點標藍色這部分,inverse表示放棄維護外鍵關系,cascade就不用說了
<hibernate-mapping package="com.cissst.it.dept.entity"> <class name="Dept" table="DEPT1"> <id name="deptno" column="DEPTNO"> <generator class="native"></generator> </id><property name="dname" column="DNAME"></property> <set name="emps" inverse="true" cascade="save-update,delete"> <key column="deptno"></key> <one-to-many class="com.cissst.it.emp.entity.Emp" /> </set> </class> </hibernate-mapping>
emp.hbm.xml
<hibernate-mapping package="com.cissst.it.emp.entity"> <class name="Emp" table="EMP1"> <id name="empno" column="EMPNO"> <generator class="native"></generator> </id> <property name="ename" column="ENAME"></property> <property name="job" column="JOB"></property> <many-to-one name="dept" class="com.cissst.it.dept.entity.Dept"/> </class> </hibernate-mapping>
測試類:
public static void main(String[] args) { //級聯保存 Session session = SessionUtil.openSession(); Transaction tx = session.getTransaction(); tx.begin(); Dept dept = new Dept(); dept.setDname("develop"); Emp emp1 = new Emp(); emp1.setEname("PECOOL"); emp1.setJob("CODE"); Emp emp2 = new Emp(); emp2.setEname("PHOEBE"); emp2.setJob("PHOTO"); HashSet<Emp> set = new HashSet<Emp>(); set.add(emp1); set.add(emp2); dept.setEmps(set); session.save(dept); tx.commit(); session.close(); }
result:
只需要保存dept對象,dept中的emp對象也會得到保存,一般1方放棄維護外鍵關系有助於改善性能,發現sql中明顯少了update語句。
hibernate---級聯保存、級聯刪除