一对一关系

1、共享主键方式

共享主键方式就是限制两个数据表的主键使用相同的值,通过主键形成一对一的映射关系。

如:学员的登录帐号信息和学员的详细分别存放到两张不同的表中。

表:


持久化类:
public class Student {

private int sid;
private String sname;
private String sex;
private int age;
private String addr;
private String college;
private String spec;
private String tel;
private String email;

private StuPwd stuPwd;

        //getters and setters;
}

public class StuPwd {

private int sid;
private String nickname;
private String password;

private Student student;

        //getters and setters;

}

Student.hbm.xml

<one-to-one name="stuPwd" class="org.itair.bean.StuPwd" cascade="all" lazy="false">
</one-to-one>
cascade 主控类的所有操作,对关联类也执行同样操作


StuPwd.hbm.xml

<one-to-one name="student" class="org.itair.bean.Student" constrained="true">
</one-to-one>
constrained 表明当前表的主键上存在一个外键的约束

2、唯一外键方式

唯一外键就是一个表的外键和另一个表的唯一主键对应形成一对一映射关系,这种一对一的关系其实就是多对一的特殊情况。
如客户详情表与地址表也属于典型的一对一关联关系; 调查实例表(pollIns)与调查口令表(pollPwd)也类似。

public class PollIns {

private int piid;
private Date pdate;
private String mgr;
private String monitor;
private int state;
private Poll poll;

        private PollPwd pollPwd;
}

public class PollPwd {

private int pid;
private String pwd;
private PollIns pollIns;
}


PollIns.hbm.xml:

<one-to-one name="pollPwd" class="org.itair.bean.PollPwd" property-ref="pollIns">
  </one-to-one>
property-ref 指定关联类的属性名

PollPwd.hbm.xml
<many-to-one name="pollIns" class="org.itair.bean.PollIns"
  lazy="false" unique="true" column="piid"
  />
unique 唯一性约束,实现一对一关联的目的。

猜你喜欢

转载自guo-jinchen.iteye.com/blog/1982107