hibernate一对一双向外键关联

一对一双向外键关联:双方都持有对方的外键关联关系。

  主控方和一对一单向外键关联的情况是一样的,主要的差异表现为,被空方需要添加:

  @OneToOne(mappedBy="card") //被控方

  主控方必须交给其中的一方去控制,因为不可以双方都同时拥有控制对方的权利,假如是这样的话是没有办法保存成功的。这就是为什么需要指定mappenBy="card"的原因。

  1、IdCard.java实体类:

package oto_bfk;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

import org.hibernate.annotations.GenericGenerator;

/*身份证类*/
@Entity
public class IdCard {

    private String pid;//身份证号
    private String sname;//学生姓名
    private Students stu;//持有主控方外键属性的引用

    @OneToOne(mappedBy="card")
    public Students getStu() {
        return stu;
    }

    public void setStu(Students stu) {
        this.stu = stu;
    }

    //无参数的构造器
    public IdCard()
    {

    }

    //带参数的构造器
    public IdCard(String pid, String sname) {
        super();
        this.pid = pid;
        this.sname = sname;
    }

    @Id//指定主键
    @Column(length=18)//指定身份证的长度
    //主键生成策略
    @GenericGenerator(name="pid",strategy="assigned")
    @GeneratedValue(generator="pid")
    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }
}

2、Students.java实体类:

package oto_bfk;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity; /*JPA注解*/
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

/**
 * 学生实体类
 * @author Administrator
 *
 */
//@Entity(name="t_students")
@Entity//表示这是一个实体类
//schema:表示数据库的名称
//name:表示数据库的表名
//Embedddable注解表示一个非Entity类,但是可以嵌入到另外一个实体类中作为属性而存在
public class Students implements Serializable{

    private IdCard card;
    private int sid;  //将学号改成字符串类型
    private String gender; //性别
    private Date birthday;//出生日期
    private String major;//专业

    public Students(IdCard card, String gender, Date birthday,
            String major) {
        super();
        this.card = card;
        this.sid = sid;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
    }

    @OneToOne(cascade=CascadeType.ALL)//表示全 级联关系
    @JoinColumn(name="pid", unique=true)
    public IdCard getCard() {
        return card;
    }

    public void setCard(IdCard card) {
        this.card = card;
    }

    @Id
    @GeneratedValue//主键自增
    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public Students()
    {

    }

}

3、hibernate.cfg.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<!-- old: http://hibernate.sourceforge.net/hibernate-configuration-3.6.dtd -->
<!-- new: http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd -->
<!--    : http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd -->
<hibernate-configuration>
<session-factory>
    <!-- 显示sql语句 -->
    <property name="show_sql">true</property>
    <property name="myeclipse.connection.profile">bookshop</property>
    <!-- <property name="connection.url">
        jdbc:mysql://localhost:3306/bookshop
        jdbc:mysql://localhost:3306/database?useUnicode=true&amp;characterEncoding=UTF-8
    </property> -->

    <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property>
    <property name="connection.username">root</property>
    <property name="connection.password">woaiwojia..123</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    <property name="hibernate.current_session_context_class">thread</property>

    <!-- 将实体类映射到数据库 -->
    <!--
    <mapping class="oto_fk.Students"/>
    <mapping class="oto_fk.IdCard"/>
     -->
    <mapping class="oto_bfk.Students"/>
    <mapping class="oto_bfk.IdCard"/>

</session-factory>
</hibernate-configuration>

4、生成数据库表结构:

@Test
    public void testShemaExport(){
        //创建Hibernate配置对象
        Configuration configuration = new Configuration().configure();

        //创建服务注册对象
        ServiceRegistry serviceRegistry =
                new ServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .buildServiceRegistry();

        //创建sessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        //生成SchemaExport对象
        SchemaExport export = new SchemaExport(configuration);
        //调用schemaExport的create生成数据库表结构
        export.create(true, true);
    }

5、Log显示:

2016-4-17 20:42:47 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
2016-4-17 20:42:47 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.21.Final}
2016-4-17 20:42:47 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
2016-4-17 20:42:47 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
2016-4-17 20:42:47 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
2016-4-17 20:42:47 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
2016-4-17 20:42:47 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
2016-4-17 20:42:47 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
2016-4-17 20:42:47 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
2016-4-17 20:42:47 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
2016-4-17 20:42:47 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8]
2016-4-17 20:42:47 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
2016-4-17 20:42:48 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
2016-4-17 20:42:48 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2016-4-17 20:42:48 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
2016-4-17 20:42:48 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: IdCard
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Students
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: IdCard
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Students
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: IdCard
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Students
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
2016-4-17 20:42:49 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
2016-4-17 20:42:49 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
2016-4-17 20:42:49 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
2016-4-17 20:42:49 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
2016-4-17 20:42:49 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8]
2016-4-17 20:42:49 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}

    alter table Students
        drop
        foreign key FK_mryi31xkbwbosevquurf60ivb

    drop table if exists IdCard

    drop table if exists Students

    create table IdCard (
        pid varchar(18) not null,
        sname varchar(255),
        primary key (pid)
    )

    create table Students (
        sid integer not null auto_increment,
        birthday datetime,
        gender varchar(255),
        major varchar(255),
        pid varchar(18),
        primary key (sid)
    )

    alter table Students
        add constraint UK_mryi31xkbwbosevquurf60ivb unique (pid)

    alter table Students
        add index FK_mryi31xkbwbosevquurf60ivb (pid),
        add constraint FK_mryi31xkbwbosevquurf60ivb
        foreign key (pid)
        references IdCard (pid)
2016-4-17 20:42:49 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8]
2016-4-17 20:42:49 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete

6、添加学生记录测试:

@Test
    public void addStudents()
    {
        //创建Hibernate配置对象
        Configuration configuration = new Configuration().configure();

        //创建服务注册对象
        ServiceRegistry serviceRegistry =
                new ServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .buildServiceRegistry();

        //创建sessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        //创建会话对象
        Session session = sessionFactory.getCurrentSession();
        //开启事务
        Transaction tx = session.beginTransaction();
        //生成一个学生身份证对象
        IdCard card = new IdCard("888888888888888888","刘德华");
        //生成一个学生对象
        Students stu = new Students(card,"男",new Date(),"计算机");
        //先保存被控表对象(身份证)
        session.save(card);
        session.save(stu);
        //提交事务
        tx.commit();

    }

7、添加学生Log:

2016-4-17 20:49:51 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
2016-4-17 20:49:52 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.21.Final}
2016-4-17 20:49:52 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
2016-4-17 20:49:52 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
2016-4-17 20:49:52 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
2016-4-17 20:49:52 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
2016-4-17 20:49:52 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
2016-4-17 20:49:52 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
2016-4-17 20:49:52 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
2016-4-17 20:49:52 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
2016-4-17 20:49:52 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8]
2016-4-17 20:49:52 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
2016-4-17 20:49:52 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
2016-4-17 20:49:52 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2016-4-17 20:49:53 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
2016-4-17 20:49:53 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: hibernate.idcard
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [pid, sname]
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: hibernate.students
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [birthday, sid, gender, pid, major]
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_mryi31xkbwbosevquurf60ivb]
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary, fk_mryi31xkbwbosevquurf60ivb, uk_mryi31xkbwbosevquurf60ivb]
2016-4-17 20:49:53 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate:
    insert
    into
        IdCard
        (sname, pid)
    values
        (?, ?)
Hibernate:
    insert
    into
        Students
        (birthday, pid, gender, major)
    values
        (?, ?, ?, ?)

  

时间: 2024-10-24 03:14:58

hibernate一对一双向外键关联的相关文章

HIBERNATE一对一双向外键联合主键关联

HIBERNATE一对一双向外键联合主键关联: 一. 创建主键类:这个主键必须实现serializedable接口和重写其中的hashCode方法和equals方法:为主键类添加一个叫做@Embeddable的注解和为实体类添加一个叫做@EmbeddabledId的注解

hibernate一对一单向外键关联

Husband类里有一个Wife类的引用 wife类: package com.oracle.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Wife { private int id; private int age; @Id @GeneratedValue public i

hibernate学习:一对一双向外键关联

一:例子 二:总结 只要是双向关联就需要加上mappedBy 在Husband中: @OneToOne @JoinColumn(name="wife_id") private Wife wife; 在Wife中 @OneToOne(mappedBy="wife") private Husband husband; mappedBy的意思讲维护关系的权利交给husband中的wife对象.在wife中就不建立对应的husband_id关系.

012一对一 唯一外键关联映射_双向(one-to-one)

²  两个对象之间是一对一的关系,如Person-IdCard(人—身份证号) ²  有两种策略可以实现一对一的关联映射 主键关联:即让两个对象具有相同的主键值,以表明它们之间的一一对应的关系:数据库表不会有额外的字段来维护它们之间的关系,仅通过表的主键来关联. 唯一外键关联:外键关联,本来是用于多对一的配置,但是如果加上唯一的限制之后,也可以用来表示一对一关联关系. 实例场景:人<—-> 身份证号(Person<->IdCard)双向:互相持有对方的引用 对象模型(唯一外键关联映

011一对一 唯一外键关联映射_单向(one-to-one)

²  两个对象之间是一对一的关系,如Person-IdCard(人—身份证号) ²  有两种策略可以实现一对一的关联映射 主键关联:即让两个对象具有相同的主键值,以表明它们之间的一一对应的关系:数据库表不会有额外的字段来维护它们之间的关系,仅通过表的主键来关联. 唯一外键关联:外键关联,本来是用于多对一的配置,但是如果加上唯一的限制之后,也可以用来表示一对一关联关系. 实例场景:人—-> 身份证号(PersonàIdCard),从IdCard看不到Person对象 对象模型实体类与一对一主键关联

Hibernate一对一双向关联映射

关键原因在于对象模型具有方向性: 单向:一端只能加载另一端,不能反过来. 双向:两端都可以加载另一端. 问题来了:如何我们想从身份证端(IdCard)加载人(Person),怎么办呢? 下面我们开始介绍一对一的双向关联映射. 映射原理 双向关联映射与单向关联映射的原理是一样的,双向关联映射并不影响存储,只影响加载.所以,双向关联映射和单向关联映射的关系模型是一样的即数据库的表结构是一样的,只是IdCard的实体类和配置文件(IdCard.hbm.xml)发生了一点点变化. 对象模型 从上图中可以

Hibernate5.2之一对一外键关联(五)

                                                 Hibernate5.2之一对一外键关联(五) 一.简介 上篇文章中笔者介绍了Hibernate关联关系中的一对一外键关联,本篇博客将介绍一对一外键关联.其实我们回过头想一想,外键关联其实就是一对多关联关系中将多的一方简化为一个,就是我们本文所要介绍的一对一的外键关联. 二.外键关联 2.1数据库表的创建 create table people ( id varchar2(255 char) not

Hibernate,关系映射的多对一单向关联、多对一双向关联、一对一主键关联、一对一外键关联、多对多关系关联

2018-11-10  22:27:02开始写 下图内容ORM.Hibernate介绍.hibername.cfg.xml结构: 下图内容hibernate映射文件结构介绍 下图内容hibernate映射文件中主键自增规则.Hibernate实例状态(瞬时状态.持久化状态.托管状态).Hibernate初始化类获取session等方法 下图内容保存数据过程 下面内容保存数据顺序.查询数据方法 get().load()和延迟加载.删除数据 下图内容删除对象顺序.修改数据顺序 下面内容关联关系映射.

hibernate5(12)注解映射[4]一对一外键关联

在实际博客站点中,文章内容的数据量非常多,它会影响我们检索文章其他数据的时间,如查询公布时间.标题.类别的等. 这个时候,我们能够尝试将文章内容存在还有一张表中,然后建立起文章--文章内容的一对一映射 一对一关联有两种方式,一种是外键关联.还有一种是复合主键关联. 外键关联 以下我们先看一个一对一单向关联的实例 /*************关联关系维护方************/ @Table(name = "t_article") @Entity public class Artic