一对一关系以丈夫和妻子模型

配置文件

妻子配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 映射配置 -->
<hibernate-mapping>
<class name="hib.po.Wife" table="t_wife">
<id name="wifeId" column="wife_id">
<generator class="uuid"></generator>
</id>
<property name="wifeName" column="wifename"></property>
</class>
</hibernate-mapping>

丈夫配置文件

 <?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 映射配置 -->
<hibernate-mapping>
<class name="hib.po.Husband" table="t_husband">
<id name="husId" column="hus_id">
<generator class="uuid"></generator>
</id> <!-- 普通属性和普通字段映射 -->
<property name="husName" column="husname"></property>
<!-- 关联关系:和Wife的one2one
特殊的many2one
-->
<many-to-one
name="wife"
class="hib.po.Wife"
column="wife_id"
unique="true"
></many-to-one>
</class>
</hibernate-mapping>

测试代码:

 /**
* @author nunu
* 测试hibernate OneToMany
*/
public class TestHibernateOneToOne { /**
* 添加数据
*/
@Test
public void addUser() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
Transaction ts = session.beginTransaction(); Husband hus1 = new Husband(null, "小明", null);
Husband hus2 = new Husband(null, "小强", null);
Wife wife1 = new Wife(null, "小花");
Wife wife2 = new Wife(null, "小丽"); session.save(hus1);
session.save(hus2);
session.save(wife1);
session.save(wife2);
System.out.println("成功");
ts.commit();
session.close();
} @Test
public void updateHusband() {
SessionFactory sf = H3Util.getSessionFactory();
Session session = sf.openSession();
Transaction ts = session.beginTransaction(); Husband hus1 = (Husband) session.get(Husband.class, "4028810a57d16fe00157d16fe3450000");
Husband hus2 = (Husband) session.get(Husband.class, "4028810a57d16fe00157d16fe3590001"); Wife wife1 = (Wife) session.get(Wife.class, "4028810a57d16fe00157d16fe3590002");
Wife wife2 = (Wife) session.get(Wife.class, "4028810a57d16fe00157d16fe3590003"); //维护
hus1.setWife(wife1);
hus2.setWife(wife2); //update:使用一级缓存中的快照,如果检测没有发生改变,不会发送任何修改语句
session.update(hus1);
session.update(hus2); System.out.println(hus1);
System.out.println(hus2); ts.commit();
session.close();
}
}
05-11 22:18