TABLE:husband
create table husband( h_id int primary key, h_name varchar(20) );
create table wife( w_id int primary key, w_name varchar(20) );
package com.lovo.po; public class HusbandPO { private int id; private String name; private WifePO myWife; //注意包含了一个妻子对象 ... other getXX setXX ... }
package com.lovo.po; public class WifePO { private int id; private String name; private HusbandPO myHus; //注意包含了一个丈夫对象 ... other getXX setXX ... }
<hibernate-mapping> <!-- 主控方 --> <class name="com.lovo.po.HusbandPO" table="husband"> <id name="id" column="h_id" type="int"> <generator class="increment"></generator> </id> <property name="name" column="h_name" type="string"></property> <!-- cascade的作用是当本身发生修改的时候,会级联的修改从表 --> <one-to-one name="myWife" class="com.lovo.po.WifePO" cascade="all"></one-to-one> </class> </hibernate-mapping>
<hibernate-mapping> <class name="com.lovo.po.WifePO" table="wife" > <id name="id" column="w_id" type="int"> <generator class="foreign"> <!-- 引用husband表的主键 --> <param name="property">myHus</param> </generator> </id> <property name="name" column="w_name" type="string"></property> <one-to-one name="myHus" class="com.lovo.po.HusbandPO" cascade="all"></one-to-one> </class> </hibernate-mapping>
create table husband( h_id int primary key, h_name varchar(20) );
create table wife( w_id int primary key, w_name varchar(20), fk_hus_id int foreign key(fk_hus_id) references husband(h_id) );
<hibernate-mapping> <class name="com.lovo.po.HusbandPO" table="husband"> <id name="id" column="h_id" type="int"> <generator class="increment"></generator> </id> <property name="name" column="h_name" type="string"></property> <one-to-one name="myWife" class="com.lovo.po.WifePO" property-ref="myHus" cascade="all"></one-to-one> <!-- property-ref 被关联到此外键的类中的对应属性的名字,若没指定,使用被关联类的主键.由于这里是唯一外键关联,所以一般要设置这里。(这里相当于是在说我妻子的老公是我,从而我妻子的结婚证编号和我的结婚证编号是一样的) --> </class> </hibernate-mapping>
<hibernate-mapping> <class name="com.lovo.po.WifePO" table="wife" > <id name="id" column="w_id" type="int"> <!-- 注意!这里的ID不在是引用husband表的ID了 --> <generator class="increment"></generator> </id> <property name="name" column="w_name" type="string"></property> <many-to-one name="myHus" class="com.lovo.po.HusbandPO" cascade="all" unique="true" column="fk_hus_id"></many-to-one> <!-- 这里是要表示一对一所以“unique="true"”是不可缺少的。column指明数据库表的外键字段 --> </class> </hibernate-mapping>