hibernate的基础学习--一对一关联
Posted 小小暮雨
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate的基础学习--一对一关联相关的知识,希望对你有一定的参考价值。
一对一关系以丈夫和妻子模型
配置文件
妻子配置文件:
<?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>
丈夫配置文件
1 <?xml version="1.0" encoding="utf-8" ?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <!-- 映射配置 --> 6 <hibernate-mapping> 7 <class name="hib.po.Husband" table="t_husband"> 8 <id name="husId" column="hus_id"> 9 <generator class="uuid"></generator> 10 </id> 11 12 <!-- 普通属性和普通字段映射 --> 13 <property name="husName" column="husname"></property> 14 <!-- 关联关系:和Wife的one2one 15 特殊的many2one 16 --> 17 <many-to-one 18 name="wife" 19 class="hib.po.Wife" 20 column="wife_id" 21 unique="true" 22 ></many-to-one> 23 </class> 24 </hibernate-mapping>
测试代码:
1 /** 2 * @author nunu 3 * 测试hibernate OneToMany 4 */ 5 public class TestHibernateOneToOne { 6 7 /** 8 * 添加数据 9 */ 10 @Test 11 public void addUser() { 12 SessionFactory sf = H3Util.getSessionFactory(); 13 Session session = sf.openSession(); 14 Transaction ts = session.beginTransaction(); 15 16 Husband hus1 = new Husband(null, "小明", null); 17 Husband hus2 = new Husband(null, "小强", null); 18 Wife wife1 = new Wife(null, "小花"); 19 Wife wife2 = new Wife(null, "小丽"); 20 21 session.save(hus1); 22 session.save(hus2); 23 session.save(wife1); 24 session.save(wife2); 25 System.out.println("成功"); 26 ts.commit(); 27 session.close(); 28 } 29 30 @Test 31 public void updateHusband() { 32 SessionFactory sf = H3Util.getSessionFactory(); 33 Session session = sf.openSession(); 34 Transaction ts = session.beginTransaction(); 35 36 Husband hus1 = (Husband) session.get(Husband.class, "4028810a57d16fe00157d16fe3450000"); 37 Husband hus2 = (Husband) session.get(Husband.class, "4028810a57d16fe00157d16fe3590001"); 38 39 Wife wife1 = (Wife) session.get(Wife.class, "4028810a57d16fe00157d16fe3590002"); 40 Wife wife2 = (Wife) session.get(Wife.class, "4028810a57d16fe00157d16fe3590003"); 41 42 //维护 43 hus1.setWife(wife1); 44 hus2.setWife(wife2); 45 46 //update:使用一级缓存中的快照,如果检测没有发生改变,不会发送任何修改语句 47 session.update(hus1); 48 session.update(hus2); 49 50 System.out.println(hus1); 51 System.out.println(hus2); 52 53 ts.commit(); 54 session.close(); 55 } 56 }
以上是关于hibernate的基础学习--一对一关联的主要内容,如果未能解决你的问题,请参考以下文章