5.一对一映射

一对一的映射关系,如:person--idCard
设计:先设计person表,再设计id_card表,且id_card表的主键等同与person的主键id,即直接使用person表的id
 
person.java
public class Person {
   private int id;
   private String name;
   private IdCard idCard;
}
 
IdCard.java
public class IdCard {
   private int id;
   private String name;
   private Person person;
}
 
映射文件:
Person.hbm.xml
< class name ="Person" >
     < id name ="id" >
       < generator class ="native" />
     </ id >
     < property name ="name" />
     < one-to-one name ="idCard" />
   </ class >
 
IdCard.hbm.xml
 
< class name ="IdCard" table ="id_card" >
     < id name ="id" >
      <!-- 声明该主键id是通过自身的person.id获得,即映射到person的主键id -->        < generator class ="foreign" >
         < param name ="property" >person </ param >
       </ generator >
     </ id >
     < property name ="name" />
     < one-to-one name ="person" />
   </ class >
 
 
测试代码:
      s = HibernateUtils.getSession();

      IdCard ic = new IdCard();
      ic.setUsefulLife( "2009");

      Person p = new Person();
      p.setName( "p1");
      p.setIdCard(ic);

      ic.setPerson(p);

      tx = s.beginTransaction();
      s.save(ic);
      s.save(p);
      tx.commit();
 
 
保存时,由于idcard的主键是映射到person的id,因此如果不为idcard设定person,则无法更新数据表,相反的,由于person的idcard属性没有参考对象,故即使idcard属性为空,也可以更新数据表
即:主对象:person,从对象:idcard
 
因此,如果保存时需要指定person的idcard属性是参考idcard表的话,那么需增加以下字段:增加person的外键约束
< one-to-one name ="person" constrained ="true" />
 
 
对于一对一的映射,也可以设置为:
多对一映射,加上限制添加:unique="true"
 
即:
< class name ="IdCard" table ="id_card" >
     < id name ="id" >
       < generator class ="native" />
      <!-- 声明该主键id是通过自身的person.id属性获得
      <generator class="foreign">
        <param name="property">person</param>
      </generator>
        -->
     </ id >
     < property name ="usefulLife" />
    <!-- 对person_id增加唯一性约束,以确保与person_id的映射 -->
     < many-to-one name ="person" column ="person_id" unique ="true" />
    <!-- <one-to-one name="person" /> -->
   </ class >
 
此时,person配置修改为:
   < class name ="Person" >
     < id name ="id" >
       < generator class ="native" />
     </ id >
     < property name ="name" />
    <!-- 增加参考对象:person -->
     < one-to-one name ="idCard" property-ref ="person" />
   </ class >

你可能感兴趣的:(职场,休闲,一对一映射)