一对一关联关系基于主键、外键映射的例子
以Department 和Manager为例。怕忘了就当笔记
下面的是基于主键的
Department类
<hibernate-mapping> <class name="com.zcd.exercise.oneToOne.primary.Department" table="DEPARTMENTS"> <id name="deptId" type="java.lang.Integer"> <column name="DEPT_ID" /> <generator class="foreign" > <param name="property">mgr</param> </generator> </id> <property name="deptName" type="java.lang.String"> <column name="DEPT_NAME" /> </property> <!-- 使用many-to-one 来映射1-1关联关系 --> <one-to-one name="mgr" class="com.zcd.exercise.oneToOne.primary.Manager" constrained="true"></one-to-one> </class> </hibernate-mapping>
Manager类
<hibernate-mapping> <class name="com.zcd.exercise.oneToOne.primary.Manager" table="MANAGERS"> <id name="mgrId" type="java.lang.Integer"> <column name="MGR_ID" /> <generator class="native" /> </id> <property name="mgrName" type="java.lang.String"> <column name="MGR_NAME" /> </property> <!-- 映射1-1关联关系:在对应的数据表中已经有外键了,当前持久化类使用one-to-one进行映射 --> <!-- 没有外键的一端需要使用one-to-one元素, property-ref属性使用别关联实体主键以外的字段作为关联字段 --> <one-to-one name="dept" class="com.zcd.exercise.oneToOne.primary.Department"></one-to-one> </class> </hibernate-mapping>
下面是基于外键的
Department类
<hibernate-mapping> <class name="com.zcd.exercise.oneToOne.foreign.Department" table="DEPARTMENTS"> <id name="deptId" type="java.lang.Integer"> <column name="DEPT_ID" /> <generator class="native" /> </id> <property name="deptName" type="java.lang.String"> <column name="DEPT_NAME" /> </property> <!-- 使用many-to-one 来映射1-1关联关系 --> <many-to-one name="mgr" class="com.zcd.exercise.oneToOne.foreign.Manager" column="MGR_ID" unique="true"></many-to-one> </class> </hibernate-mapping>
Manager类
<hibernate-mapping> <class name="com.zcd.exercise.oneToOne.foreign.Manager" table="MANAGERS"> <id name="mgrId" type="java.lang.Integer"> <column name="MGR_ID" /> <generator class="native" /> </id> <property name="mgrName" type="java.lang.String"> <column name="MGR_NAME" /> </property> <!-- 映射1-1关联关系:在对应的数据表中已经有外键了,当前持久化类使用one-to-one进行映射 --> <!-- 没有外键的一端需要使用one-to-one元素, property-ref属性使用别关联实体主键以外的字段作为关联字段 --> <one-to-one name="dept" class="com.zcd.exercise.oneToOne.foreign.Department" property-ref="mgr"></one-to-one> </class> </hibernate-mapping>