Hibernate基础------》映射关系---》one2one

来源:互联网 发布:720全景源码 编辑:程序博客网 时间:2024/05/14 18:13
                人们常说 One2one是特殊的one2many  其实这种说法很形象
one2one就是两个持久类都引用彼此类本身作为一个组件,而且不以集合形式出现
        例如:  在wife类下的private Husband husband;
               在Husband类下的private Wife wife;
               
            
    配置文件如下
      我设置Husband为控制类
            Husband类的配置<many-to-one name="wife" class="Wife" cascade="all" column="h_w_id"></many-to-one>
    
      Wife类配置
            <one-to-one name="husband" class="Husband">
        
        
        运行类
        Husband hu = new Husband();
        hu.setAge(26);
        hu.setName("老罗");
        
        Wife wi = new Wife();
        wi.setAge(24);
        wi.setName("小罗");
        
        
        hu.setWife(wi);
        
        session.save(hu);
        
              
        
one2one的第二种写法
在第一种的基础上两个po类不变,改变的只是控制类的配置
将控制类的配置改变为
        <id name="id" column="id">
           <generator class="foreign"><!--foreign仅在one2one的该方法上使用,即增加主键外键的功能 -->
                   <param name="property">wife</param>
           </generator>
        </id>
        <property name="name" column="name"></property>
        <one-to-one name="wife"  class="wife"  constrained="true" cascade="all"></one-to-one>
        </class>
        constrained即指定在主键上增加外键功能和上面many-to-one one-to-one方法里的unique相似
即主键又是外键
但是我个人感觉该方法关联关系不直观。        
       


1 0