7.4.2. 一对一(one to one)

基于外键关联的双向一对一关联也很常见。

  1. <class name="Person">
  2. <id name="id" column="personId">
  3. <generator class="native"/>
  4. </id>
  5. <many-to-one name="address"
  6. column="addressId"
  7. unique="true"
  8. not-null="true"/>
  9. </class>
  10. <class name="Address">
  11. <id name="id" column="addressId">
  12. <generator class="native"/>
  13. </id>
  14. <one-to-one name="person"
  15. property-ref="address"/>
  16. </class>
  1. create table Person ( personId bigint not null primary key, addressId bigint not null unique )
  2. create table Address ( addressId bigint not null primary key )

基于主键关联的一对一关联需要使用特定的id生成器。

  1. <class name="Person">
  2. <id name="id" column="personId">
  3. <generator class="native"/>
  4. </id>
  5. <one-to-one name="address"/>
  6. </class>
  7. <class name="Address">
  8. <id name="id" column="personId">
  9. <generator class="foreign">
  10. <param name="property">person</param>
  11. </generator>
  12. </id>
  13. <one-to-one name="person"
  14. constrained="true"/>
  15. </class>
  1. create table Person ( personId bigint not null primary key )
  2. create table Address ( personId bigint not null primary key )