hibernate一对一主键双向关联

时间:2021-04-30 19:37:18

关联是类(类的实例)之间的关系,表示有意义和值得关注的连接。

本系列将介绍Hibernate中主要的几种关联映射

Hibernate一对一主键单向关联
Hibernate一对一主键双向关联
Hibernate一对一外键单向关联
Hibernate一对一外键双向关联
Hibernate多对一单向关联
Hibernate多对一双向关联

Hibernate多对多关联

代码都写有注释,主要包括(核心配置文件,实体映射文件,实体类,测试类,数据库)主要操作有增删改查。

本篇主要介绍Hibernate一对一主键双向关联:

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
      <!-- 配置数据库连接驱动类 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 配置数据库连接字符串 -->
        <property name="connection.url"><![CDATA[jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8]]></property>
        <!-- 配置数据库连接用户名 -->
        <property name="connection.username">root</property>
        <!-- 配置数据库连接密码 -->
        <property name="connection.password">123456</property>
        <!-- 配置数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 配置数据库表生成策略 -->
        <!--<property name="hibernate.hbm2ddl.auto">update</property> -->
        <!-- 配置是否打印显示SQL语句 -->
        <property name="show_sql">true</property>
        <!-- 配置是否格式化显示SQL语句 -->
        <property name="format_sql">true</property>
        <!-- 配置hibernate是否自动提交事务 -->
        <!--<property name="hibernate.connection.autocommit">true</property> -->
        <!-- 配置实体类对应的映射文件 -->

        <!-- 一对一主键双向关联 -->
        <mapping resource="com/great/entity2/People.hbm.xml"></mapping>
        <mapping resource="com/great/entity2/IdCard.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

People.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.great.entity2">
    <!-- 配置实体类与数据库表的映射关系 -->
    <class name="com.great.entity2.People" table="people">
        <!-- 配置主键映射关系 -->
        <id name="id" column="id" type="int">
            <!-- 配置主键生成策略 -->
            <generator class="foreign">
                <param name="property">idCard</param>
            </generator>
        </id>
        <!-- 配置属性和表字段映射关系 -->
        <property name="pName" column="pName" type="string"></property>
        <one-to-one name="idCard" class="com.great.entity2.IdCard"
            cascade="all"></one-to-one>
    </class>
</hibernate-mapping>

IdCard.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.great.entity2">
    <class name="IdCard" table="idcard">
        <id name="id" column="id" type="int">
            <generator class="native">
            </generator>
        </id>
        <!-- 配置属性和表字段映射关系 -->
        <property name="cardCode" column="cardCode" type="string"></property>
        <one-to-one class="com.great.entity2.People" name="people"
            cascade="all"></one-to-one>
    </class>
</hibernate-mapping>

People.java

package com.great.entity2;

public class People {
    // 一对一主键关联
    private int id;
    private String pName;
    private IdCard idCard;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getpName() {
        return pName;
    }

    public void setpName(String pName) {
        this.pName = pName;
    }

    public IdCard getIdCard() {
        return idCard;
    }

    public void setIdCard(IdCard idCard) {
        this.idCard = idCard;
    }

}

IdCard.java

package com.great.entity2;

public class IdCard {
    private int id;
    private String cardCode;
    private People people;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCardCode() {
        return CardCode;
    }

    public void setCardCode(String cardCode) {
        CardCode = cardCode;
    }

    public People getPeople() {
        return people;
    }

    public void setPeople(People people) {
        this.people = people;
    }

}

TestOneToOneUniqueBoth.java(测试类)

package com.great.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.great.entity2.IdCard;
import com.great.entity2.People;

public class TestOneToOneUniqueBoth {
    static Session session;

    // 一对一主键双向关联
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        // 加载hibernate主配置文件
        Configuration cfg = new Configuration().configure();
        // 构建session工厂
        SessionFactory sf = cfg.buildSessionFactory();
        // 打开session
        session = sf.openSession();
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        // 关闭session,释放资源
        session.close();
    }

    // select1,通过people查询idcard
    @Test
    public void testOneToOneSelect1() {
        People people = (People) session.get(People.class, 1);
        System.out.println("身份证号码:" + people.getIdCard().getCardCode());
        System.out.println("姓名:" + people.getpName());
    }

    // select2, 通过idcard查询people
    @Test
    public void testOneToOneSelect2() {
        IdCard idCard = (IdCard) session.get(IdCard.class, 1);
        System.out.println("身份证号码:" + idCard.getCardCode());
        System.out.println("姓名:" + idCard.getPeople().getpName());
    }

    // insert1, 通过people插入数据 ,两条insert,【先insert idCard,后insert
    // people,涉及键的问题,必须顺序的保存数据,而insert语句就是按顺序的,和select,delete,update不一样】
    @Test
    public void testOneToOneSave1() {
        Transaction ts = session.beginTransaction();
        // 设置idcard
        IdCard idCard = new IdCard();
        idCard.setCardCode("411487199505051234");
        // 设置people
        People people = new People();
        people.setpName("王胖");
        // 互相保存
        idCard.setPeople(people);
        people.setIdCard(idCard);
        // 保存idcard,必须保存idCard,保存People出错,Hibernate这次首先持久化了people对象
        // 由于people表中的id字段建立了外键关系,故持久化失败.
        session.save(idCard);
        ts.commit();
    }

    /*
     * delete1 通过删除idCard删除数据,一条select,两条delete,先delete people,再delete idCard
     * ,【涉及键的问题,与select有关,所以只能有一种delete的方法】
     */
    @Test
    public void testOneToOneDelete1() {
        Transaction ts = session.beginTransaction();
        IdCard idCard = (IdCard) session.get(IdCard.class, 10);
        session.delete(idCard);
        ts.commit();
    }

    // delete2 通过删除idCard删除数据,
    // @Test
    // public void testOneToOneDelete2() {
    // Transaction ts = session.beginTransaction();
    // People people = (People) session.get(People.class, 8);
    // session.delete(people);
    // ts.commit();
    // }

    /*
     * update1 ,通过idCard更新数据,发出一条select,两条update ,先update people,再update inCard
     * 【因为要想update idCard,就得update people,不涉及键的问题,只与select有关】
     */
    @Test
    public void testOneToOneUpdate1() {
        Transaction ts = session.beginTransaction();
        IdCard idCard = (IdCard) session.get(IdCard.class, 8);
        idCard.setCardCode("123456789");
        idCard.getPeople().setpName("张起灵aaa");
        session.update(idCard);
        ts.commit();
    }

    /*
     * update2 ,通过people更新数据,发出一条select,两条update ,先update idCard,再update
     * people【因为要想update people,就得update idCard,不涉及键的问题,只与select有关】
     */
    @Test
    public void testOneToOneUpdate2() {
        Transaction ts = session.beginTransaction();
        People people = (People) session.get(People.class, 8);
        people.setpName("小哥");
        people.getIdCard().setCardCode("66666");
        session.update(people);
        ts.commit();
    }

}

数据库:

people表

两个字段id pName

idcard表

两个字段id cardCode

注意:在people表上建立外键关系。