hibernate一对一外键双向关联

时间:2022-11-21 19:38:48

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

本系列将介绍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/test111?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/entity5/People.hbm.xml"></mapping> <mapping resource="com/great/entity5/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.entity5">
    <!-- 配置实体类与数据库表的映射关系 -->
    <class name="People" table="people1">
        <!-- 配置主键映射关系 -->
        <id name="id" column="id" type="int">
            <!-- 配置主键生成策略 这个主键生成策略并没有什么影响 -->
            <generator class="native">
            </generator>
        </id>
        <!-- 配置属性和表字段映射关系 一对外键一双向关联 -->
        <property name="pName" column="pName" type="string"></property>
        <many-to-one name="idCard" unique="true" cascade="all">
            <column name="card_id"></column>
        </many-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.entity5">
    <class name="IdCard" table="idcard1">
        <id name="card_id" column="id" type="int">
            <generator class="identity">
            </generator>
        </id>
        <!-- 配置属性和表字段映射关系 一对一外键双向关联 -->
        <property name="cardCode" column="cardCode" type="string"></property>
        <one-to-one name="people" class="com.great.entity5.People"
            cascade="all" property-ref="idCard" />
    </class>
</hibernate-mapping>

People.java

package com.great.entity5;

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.entity5;

public class IdCard {
    // 一对一外键双向关联
    private int card_id;
    private String cardCode;
    private People people;

    public int getCard_id() {
        return card_id;
    }

    public void setCard_id(int card_id) {
        this.card_id = card_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;
    }
}

TestOneToOneForeignBoth.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.entity5.IdCard;
import com.great.entity5.People;

public class TestOneToOneForeignBoth {
    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
    @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
    @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来插入数据
    @Test
    public void testOneToOneSave1() {
        Transaction ts = session.beginTransaction();
        IdCard idCard = new IdCard();
        idCard.setCardCode("124567891234566");
        People people = new People();
        people.setpName("张起灵2");
        idCard.setPeople(people);// 可加可不加
        people.setIdCard(idCard);
        session.save(people);
        ts.commit();
    }

    // insert2数据,通过保存inCard来插入数据
    @Test
    public void testOneToOneSave2() {
        Transaction ts = session.beginTransaction();
        IdCard idCard = new IdCard();
        idCard.setCardCode("124567891234566");
        People people = new People();
        people.setpName("张起灵2");
        people.setIdCard(idCard);// 必须加,否则失败
        idCard.setPeople(people);
        session.save(idCard);
        ts.commit();
    }

    // delete1数据,删除people,级联删除inCard。发出两条查询两条删除语句
    @Test
    public void testOneToOneDelete1() {
        Transaction ts = session.beginTransaction();
        People people = (People) session.get(People.class, 12);
        session.delete(people);
        ts.commit();
    }

    /*
     * delete2数据,通过删除idCard,级联删除people.
     * delete数据。发出两条查询两条删除语句,也是先删除people再删除idCard
     */
    @Test
    public void testOneToOneDelete2() {
        Transaction ts = session.beginTransaction();
        IdCard idCard = (IdCard) session.get(IdCard.class, 14);
        session.delete(idCard);
        ts.commit();
    }

    // 更新数据1,通过people进行更新
    @Test
    public void testOneToOneUpdate1() {
        Transaction ts = session.beginTransaction();
        People people = (People) session.get(People.class, 11);
        people.setpName("张起灵1");
        people.getIdCard().setCardCode("511381199612120254");
        /*
         * session.update(people);
         * update和saveOrUpdate的区别在于后者在数据库中不存在此对象的情况下插入,所以效率低。
         */
        session.saveOrUpdate(people);
        ts.commit();
    }

    // 更新数据2,通过idCard进行更新
    @Test
    public void testOneToOneUpdate2() {
        Transaction ts = session.beginTransaction();
        IdCard idCard = (IdCard) session.get(IdCard.class, 8);
        idCard.getPeople().setpName("张起灵3");
        idCard.setCardCode("311381199612120254");
        session.update(idCard);
        ts.commit();
    }
}

数据库:

people1表

三个字段id pName card_id(外键)

idcard1表

两个字段id cardCode

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