这里使用学生和学生的详细信息表来表述,OneToOne有三种配置
1、主键关联
主键关联是最复杂也是最常用的关联方式。
配置如下:studentInfo主键生成策略,使用当前对象中student属性的主键来作为本对象的主键
@Id @GeneratedValue(generator="pkGenerator") @GenericGenerator(name = "pkGenerator", strategy = "foreign", parameters = @Parameter(name = "property", value = "student")) private Integer id;
//optional 关联属性可以为空 接连关系由StudentInfo的属性student维持
@OneToOne(mappedBy="student",cascade=CascadeType.ALL,optional=true) //@Cascade(value={org.hibernate.annotations.CascadeType.ALL}) private StudentInfo studentInfo ; //optional 关联属性不能为空 @OneToOne(cascade={CascadeType.PERSIST,CascadeType.MERGE},optional=false) @PrimaryKeyJoinColumn private Student student;
测试代码:
@Test public void addStudent() { Student student = new Student("zyn", 22,20072724L); StudentInfo info = new StudentInfo("3444444","成都市"); info.setStudent(student); this.studentInfoDao.save(info); }
2、外键关联,只需要修改StudentInfo中的student属性
通过外键student_id关联
@OneToOne(cascade={CascadeType.PERSIST,CascadeType.MERGE},optional=false) //@PrimaryKeyJoinColumn @JoinColumn(name="student_id",nullable=false,unique=true) private Student student;
3、中间表关联
通过中间表student_and_info关联
@OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, optional = false) @JoinTable(name="student_and_info",joinColumns = @JoinColumn(name = "info_id"), inverseJoinColumns = @JoinColumn(name = "student_id")) private Student student;