hibernate中1对1的注解配置分为:外键关联映射和主键关联映射

1.外键配置

//一方
@Entity
@Table(name="test_classinfo")
public class ClassInfo {
  @Id
  @SequenceGenerator(name="seqClassInfo",sequenceName="seq_test_classinfo")
  @GeneratedValue(generator="seqClassInfo")
  private Integer cid;
  private String cname;
  @OneToOne(mappedBy="classInfo")
  private Students students;

  set,get方法省略

}

//多方

@Entity
@Table(name="test_student")
public class Students {
  @Id
  @SequenceGenerator(name="seqStudents",sequenceName="seq_test_student")
  @GeneratedValue(generator="seqStudents")
  private Integer sid;
  private String sname;
  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name="cid",unique=true)
  private ClassInfo classInfo;

  set,get方法省略

}

 

2.主键关联映射

@Entity
@Table(name="test_husband")
public class Husband {
  @Id
  @SequenceGenerator(name="seqHusband",sequenceName="seq_test_husband")
  @GeneratedValue(generator="seqHusband")
  @Column(name="marriage_id")
  private Integer marriageId;
  private String hname;
  @OneToOne(cascade=CascadeType.ALL)
  @PrimaryKeyJoinColumn               //@PrimaryKeyJoinColumn :说明Wife的主键是由Husband的主键决定
  private Wife wife;

  set,get方法省略

}

@Entity
@Table(name="test_wife")
public class Wife {
  /*
  * <id name="marriageId" column="marriage_Id" >
      <generator class="foreign">
        <param name="property">husband</param>
      </generator>
   </id>
  */
  @Id
  @GenericGenerator(name="seqwife",strategy="foreign",parameters={@Parameter(name="property",value="husband")})
  @GeneratedValue(generator="seqwife")
  @Column(name="marriage_id")
  private Integer marriageId;
  private String wname;
  @OneToOne(mappedBy="wife")
  private Husband husband;

  set,get方法省略

}