一.一对一关联的概念:

一对一之间的关联是指:两张表中的信息是一对一的关系,比如我们每个人和身份证的关系,一个人对应一张身份证,一张身份证也只能对应一个人。

Hibernate提供了两种映射一对一关联关系的方式:按照外键映射和按照主键映射。

在下面的例子中我们分别以两张表:员工表和员工档案表为例:介绍这两种映射关系方式。

二.按外键映射

1.关联的外键可存放于任意一端,并在存放外键的一端增加<many-to-one>元素,能够增加唯一约束实现一对一关联。
        2.<many-to-one>元素的unique="true"属性,表示1-1关联;name属性指定关联属性的属性名
        3.另一端需要使用<one-to-one>元素,在元素中使用"property-ref"属性(可不加),指定使用被关联实体主键以外的字段作为关联字段。

I.首先建立两张表的实体类:

Users1:

package cn.entity;
/**
 * 员工账号实体类
 * @author hyj
 *
 */
public class Users1 {
    private Integer userid;//员工账号
    private String username;//员工名称
    private String userpass;//员工密码
    private Resume1 resume1;//员工的档案
    public Users1() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Users1(String username, String userpass) {
        super();
        this.username = username;
        this.userpass = userpass;
    }

    public Users1(Integer userid, String username, String userpass,
            Resume1 resume1) {
        super();
        this.userid = userid;
        this.username = username;
        this.userpass = userpass;
        this.resume1 = resume1;
    }
    public Integer getUserid() {
        return userid;
    }
    public void setUserid(Integer userid) {
        this.userid = userid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getUserpass() {
        return userpass;
    }
    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }
    public Resume1 getResume1() {
        return resume1;
    }
    public void setResume1(Resume1 resume1) {
        this.resume1 = resume1;
    }

}

Resume1:

package cn.entity;
/**
 * 员工档案实体类
 * @author hyj
 *
 */
public class Resume1 {
    private Integer resid;
    private String resname;//档案名称
    private String rescardno;//档案编号
    private Users1 users1;//所属员工
    public Resume1() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Resume1(Integer resid, String resname, String rescardno,
            Users1 users1) {
        super();
        this.resid = resid;
        this.resname = resname;
        this.rescardno = rescardno;
        this.users1 = users1;
    }

    public Resume1(String resname, String rescardno) {
        super();
        this.resname = resname;
        this.rescardno = rescardno;
    }
    public Integer getResid() {
        return resid;
    }
    public void setResid(Integer resid) {
        this.resid = resid;
    }
    public String getResname() {
        return resname;
    }
    public void setResname(String resname) {
        this.resname = resname;
    }
    public String getRescardno() {
        return rescardno;
    }
    public void setRescardno(String rescardno) {
        this.rescardno = rescardno;
    }
    public Users1 getUsers1() {
        return users1;
    }
    public void setUsers1(Users1 users1) {
        this.users1 = users1;
    }

}

II.建立两个实体类的映射文件:

Resume1.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
       <hibernate-mapping package="cn.entity">
       <class name="Resume1" table="Resume1">
          <id name="resid" column="resid">
            <generator class="native"></generator>
          </id>
       <property name="resname" column="resname" type="string"></property>
     <property name="rescardno" column="rescardno" type="string"></property>
    <many-to-one name="users1" class="Users1" column="RESUSERID" cascade="all" unique="true"></many-to-one>
       </class>
       </hibernate-mapping>

Users1.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
       <hibernate-mapping package="cn.entity">
       <class name="Users1" table="Users1">
          <id name="userid" column="USERID">
            <generator class="native"></generator>
          </id>
       <property name="username" column="username" type="string"></property>
     <property name="userpass" column="userpass" type="string"></property>
     <one-to-one name="resume1" class="Resume1" property-ref="users1"></one-to-one>
       </class>
       </hibernate-mapping>

III:建立测试类:

package cn.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.entity.Resume1;
import cn.entity.Users1;
import cn.util.HibernateUtil;

public class HappyTest {
    /**
     * 添加信息
     */
     @Test
     public void addInfoTest(){
          //1.获取session对象
         Session session=HibernateUtil.currentSession();
         //2.开启事务
         Transaction tx = session.beginTransaction();
         //3.准备一个用户对象
         Users1 users1=new Users1("hyj","123");
         //4.创建一个档案对象
         Resume1 resume1=new Resume1("高级机密档案","hyj0819");
         //5.让用户归属档案,档案归属用户
         users1.setResume1(resume1);
         resume1.setUsers1(users1);
         //6.session.save保存档案即可,应为cascade的属性值为all,保存档案的同时自动保存用户
         session.save(resume1);
         //7.提交事务
         tx.commit();
         //8.关闭session
         HibernateUtil.closeSession();
         System.out.println("添加成功");
     }

     /**
      * 查询员工档案的时候同时加载用户信息
      */
      @Test
      public void selectInfoTest(){
           //1.获取session对象
          Session session=HibernateUtil.currentSession();
          //2.获取员工档案对象
          Resume1 resume1=(Resume1)session.load(Resume1.class, 1);
            //3.根据员工档案获取用户的信息
           Users1 users1= resume1.getUsers1();
          //4.输出结果
           System.out.println("档案名称:"+resume1.getResname());
           System.out.println("用户姓名:"+users1.getUsername());
          //8.关闭session
          HibernateUtil.closeSession();
      }

}

user1表:

resume1表:

三.按主键映射

1.关联要求两个对象的主键必须保持一致,通过两个表的主键建立关联关系须外键参与。
       2.基于主键的映射策略:指一端的主键生成器使用"class="foreign""策略,表明根据"对方"的主键来生成自己的主键,自己并不能独立生成主键。<param>子元素指定使用当前持久化类的哪个属性作为"对方"。
       3.采用foreign主键生成器策略的一端增加<one-to-one>元素映射关联属性,并在<one-to-one>元素中增加constrained="true"属性;另一端也增加<one-to-one>元素映射关联属性。
       4."constrained="true""属性:指定当前持久化类对应的数据库表的主键添加一个外键约束,引用被关联的对象("对方")所对应的数据库表主键

I.首先建立两张表的实体类:

为了区分案例此表为Users2 Resume2:

Users2:

package cn.entity;
/**
 * 员工账号实体类
 * @author hyj
 *
 */
public class Users2 {
    private Integer userid;
    private String username;
    private String userpass;
    private Resume2 resume2;
    public Users2() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Users2(Integer userid, String username, String userpass,
            Resume2 resume2) {
        super();
        this.userid = userid;
        this.username = username;
        this.userpass = userpass;
        this.resume2 = resume2;
    }
    public Integer getUserid() {
        return userid;
    }
    public void setUserid(Integer userid) {
        this.userid = userid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getUserpass() {
        return userpass;
    }
    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }
    public Resume2 getResume2() {
        return resume2;
    }
    public void setResume2(Resume2 resume2) {
        this.resume2 = resume2;
    }
    public Users2(String username, String userpass) {
        super();
        this.username = username;
        this.userpass = userpass;
    }

}

Resume2:

package cn.entity;
/**
 * 员工档案实体类
 * @author hyj
 *
 */
public class Resume2 {
    private Integer resid;
    private String resname;
    private String rescardno;
    private Users2 users2;
    public Resume2() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Resume2(Integer resid, String resname, String rescardno,
            Users2 users2) {
        super();
        this.resid = resid;
        this.resname = resname;
        this.rescardno = rescardno;
        this.users2 = users2;
    }
    public Resume2(String resname, String rescardno) {
        super();
        this.resname = resname;
        this.rescardno = rescardno;
    }
    public Integer getResid() {
        return resid;
    }
    public void setResid(Integer resid) {
        this.resid = resid;
    }
    public String getResname() {
        return resname;
    }
    public void setResname(String resname) {
        this.resname = resname;
    }
    public String getRescardno() {
        return rescardno;
    }
    public void setRescardno(String rescardno) {
        this.rescardno = rescardno;
    }
    public Users2 getUsers2() {
        return users2;
    }
    public void setUsers2(Users2 users2) {
        this.users2 = users2;
    }

}

II.建立两个实体类的映射文件:

Resume2.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
       <hibernate-mapping package="cn.entity">
       <class name="Resume2" table="Resume2">
          <id name="resid" column="resid">
            <generator class="native"></generator>
          </id>
       <property name="resname" column="resname" type="string"></property>
     <property name="rescardno" column="rescardno" type="string"></property>
    <one-to-one  name="users2" cascade="all" class="Users2"/>
       </class>

       </hibernate-mapping>

Users2.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
       <hibernate-mapping package="cn.entity">
       <class name="Users2" table="Users2">
          <id name="userid" column="USERID" >
        <generator class="foreign">
          <param name="property">resume2</param>
        </generator>
          </id>
       <property name="username" column="username" type="string"></property>
     <property name="userpass" column="userpass" type="string"></property>
     <one-to-one name="resume2" class="Resume2" constrained="true"></one-to-one>
       </class>

       </hibernate-mapping>

III.建立测试类:

package cn.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.entity.Resume2;
import cn.entity.Users2;
import cn.util.HibernateUtil;

public class HappyTest {
    /**
     * 添加信息
     */
     @Test
     public void addInfoTest(){
          //1.获取session对象
         Session session=HibernateUtil.currentSession();
         //2.开启事务
         Transaction tx = session.beginTransaction();
         //3.准备一个用户对象
         Users2 users2=new Users2("hyj","123");
         //4.创建一个档案对象
         Resume2 resume2=new Resume2("高级机密档案","hyj0819");
         //5.让用户归属档案,档案归属用户
         users2.setResume2(resume2);
         resume2.setUsers2(users2);
         //6.session.save保存档案即可,应为cascade的属性值为all,保存档案的同时自动保存用户
         session.save(resume2);
         //7.提交事务
         tx.commit();
         //8.关闭session
         HibernateUtil.closeSession();
         System.out.println("添加成功");
     }

     /**
      * 查询员工档案的时候同时加载用户信息
      */
      @Test
      public void selectInfoTest(){
           //1.获取session对象
          Session session=HibernateUtil.currentSession();
          //2.获取员工档案对象
          Resume2 resume2=(Resume2)session.load(Resume2.class, 3);
            //3.根据员工档案获取用户的信息
           Users2 users2= resume2.getUsers2();
          //4.输出结果
           System.out.println("档案名称:"+resume2.getResname());
           System.out.println("用户姓名:"+users2.getUsername());
          //8.关闭session
          HibernateUtil.closeSession();
      }

}

users2表

resume2表

最新文章

  1. NMAP分布式扫描工具dnmap
  2. MVC中的一些坑
  3. latex中页面距离的设置
  4. TF-IDF 加权及其应用
  5. ios block中引用self
  6. TFS客户端登录用户修改
  7. Resources are low on NN. Please add or free up more resources then turn off safe mode manually.
  8. CF 560e Gerald and Giant Chess
  9. [每日一题] 11gOCP 1z0-053 :2013-10-12 RESULT_CACHE在哪个池?.............................44
  10. 项目中 mysql中的内容关于上架时间和下架时间
  11. Mvc中DropDownList 和DropDownListFor的常用方法
  12. 一維條碼編碼規則(1D Barcode)
  13. sessionStorage用于分页,瀑布流和存储用户数据等
  14. 自学Python的经验之谈,学好Python的捷径
  15. PADS导入DXF板框,不能将开放的2D线转换成闭合的板框错误
  16. linux服务器启动报错UNEXPECTED INCONSISTENCY解决方法
  17. 把旧系统迁移到.Net Core 2.0 日记(11) -- Authentication 认证 claimsIdentity 对比 之前的FormAuthentication
  18. bzoj4937: [Ceoi2016]popeala
  19. oracle listagg within group
  20. iOS 应用程序目录结构

热门文章

  1. Pythonn new-style class and old-style class
  2. 和redis谈一场恋爱(第一天邂逅)
  3. js011-DOM扩展
  4. centos设置编码
  5. -[UIWindow viewForFirstBaselineLayout]: unrecognized selector sent to instance
  6. Robot Framework--09 分支与循环的用法
  7. C# 6.0可能的新特性
  8. 数据库操作事务IsolationLevel 枚举
  9. Nginx 支持 WAF 防护功能实战
  10. oracle union 注入工具