背景:项目中长期使用,却并没有整理,抽出零碎时间将其整理如下,以供大家参考。
首先对下面两个类做一个说明:
seal对象,BranchInfo对象,两者是多对一关系,一个分支机构可以有多个seal,一个seal属于一个分支机构。UML图如下:
Hibernate映射文件如下:
BranchInfo.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.indigopacific.iessportal.persistent.BranchInfo"
table="tbranchinfo" dynamic-update="true" dynamic-insert="true"
select-before-update="false" lazy="false">
<id name="id" column="id" type="long">
<generator class="increment" />
</id>
<property name="address" type="string" column="address"
not-null="false" unique="false" />
<set name="sealSet" cascade="none" lazy="true"
outer-join="true" inverse="true">
<key column="branchInfoId" />
<one-to-many
class="com.indigopacific.iessportal.persistent.Seal" />
</set>
</class>
</hibernate-mapping>
Seal.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.indigopacific.iessportal.persistent.Seal"
table="tseal" dynamic-update="true" dynamic-insert="true"
select-before-update="false" lazy="false">
<id name="id" column="id" type="long">
<generator class="increment"/>
</id>
<property name="sealName" type="string" column="sealName"
not-null="false" unique="false" />
<one-to-one name="sealData"
class="com.indigopacific.iessportal.persistent.SealData"
cascade="save-update" lazy="proxy" />
<set name="sealModel" cascade="save-update" lazy="true"
outer-join="false" inverse="true">
<key column="sealId" />
<one-to-many
class="com.indigopacific.iessportal.persistent.SealModel" />
</set>
<many-to-one name="branchInfo" column="branchInfoId"
class="com.indigopacific.iessportal.persistent.BranchInfo"
cascade="delete" outer-join="false" lazy="false">
</many-to-one>
</class>
</hibernate-mapping>
测试工具Junit(http://www.junit.org/)建模工具EA(http://www.crsky.com/soft/20452.html)
数据库MySql
主要讲解many-to-one中inverse和cascade的区别。BranchInfo的添加,更新,删除来说明inverse和cascade的区别。
1、保存BranchInfo,设置BranchInfo.hbm.xml中inverse=false不设置默认为false,cascade=save-update
测试代码如下:
BranchInfo branchInfo = new BranchInfo();
branchInfo.setAddress("bj3");
Set<Seal> sealSet = new HashSet<Seal>();
Seal seal = new Seal();
seal.setSealData(null);
seal.setSealModels(null);
seal.setSealName("sealName4");
sealSet.add(seal);
branchInfo.setSealSet(sealSet);
session.save(branchInfo);
输出sql语句如下:
Hibernate: insert into tbranchinfo (address, depname, id) values (?, ?, ?)
Hibernate: insert into tseal (sealName, id) values (?, ?)
Hibernate: update tseal set branchInfoId=? where id=?
说明:
由于设置cascade=save-update因此当保存branchinfo时会级联保存seal,
又因为inverse默认为false因此branchinfo也就是一端会维护级联关系,
因此出现更新tseal表的语句。