hibernate 中1对1的关系分为外键关联和主键关联

外键关联:

//多方

public class Students {                                                                           
  private Integer stuId;
  private String stuName;
  private Integer age;
  private ClassInfo classInfo;

     get.set方法省略

}

配置:

<class name="Students" table="test_Students" >
  <id name="stuId" column="stu_id" >
    <generator class="sequence">
      <param name="sequence">seq_test_Students</param>
    </generator>
  </id>
  <property name="stuName" column="stu_name" />
  <property name="age" />
  <!-- 多对1的关系 -->
  <many-to-one name="classInfo" class="ClassInfo" column="cid" unique="true" />
</class>

//一方

public class ClassInfo {
  private Integer cid;
  private String cname;
  private Students students;

     get.set方法省略

}

ClassInfo.hbm.xml配置:

<class name="ClassInfo" table="test_Class_Info" >
  <id name="cid" >
    <generator class="sequence">
      <param name="sequence">seq_test_Class_Info</param>
    </generator>
  </id>
  <property name="cname" />
  <!-- 一对一的关系 -->
  <one-to-one name="students" class="Students" cascade="all" />
</class>

 

主键关联:

/**
* 主键生成方
*/
public class Husband {
  private Integer marriageId;
  private String hname;
  private Wife wife;

  get.set方法省略

}

配置:

<class name="Husband" table="test_husband" >
  <id name="marriageId" column="marriage_Id" >
    <generator class="sequence">
      <param name="sequence">seq_test_husband</param>
    </generator>
  </id>
  <property name="hname" />
  <!-- 一对一的关系 -->
  <one-to-one name="wife" class="Wife" cascade="all" />
</class>

/**
* 主键跟随方
*/
public class Wife {
  private Integer marriageId;
  private String wname;
  private Husband husband;

  get.set方法省略

}

配置:

<class name="Wife" table="test_wife" >
   <id name="marriageId" column="marriage_Id" >
    <generator class="foreign">
      <param name="property">husband</param>
    </generator>
  </id>
  <property name="wname" />
  <!-- 一对一的关系 -->
  <one-to-one name="husband" class="Husband"/>
</class>