1、Annotation 注解版

1.1、创建Husband类和Wife类

 package com.shore.model;

 import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne; import org.hibernate.annotations.Type; /**
* @author DSHORE/2019-9-18
* 一对一,双向关联(注解版)
*/
@Entity
public class Husband {//主表 类
private Integer id;
private String name;
private Boolean sex;
private Wife wife; @Id
@GeneratedValue(strategy = GenerationType.AUTO) //主键生成策略(使用test()测试时,必须加上这个,否会报错:id生成错误)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} @Type(type = "yes_no") //数据库中,会以Y/N的形式插入到sex字段中
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
} @OneToOne(mappedBy="husband")//映射:从表wife映射主表husband。如果不要(mappedBy="husband"),主表husband将会多一个没必要的字段wife_id(外键)
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
}

Wife类

 package com.shore.model;

 import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne; import org.hibernate.annotations.Type; /**
* @author DSHORE/2019-9-18
* 一对一,双向关联(注解版)
*/
@Entity
public class Wife {//从表
private Integer id;
private String name;
private Boolean sex;
private Husband husband; @Id
@GeneratedValue(strategy = GenerationType.AUTO) //主键生成策略(使用test1测试时,必须加上这个,否会报错:id生成错误)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} @Type(type = "yes_no") //数据库中,会以Y/N的形式插入到sex字段中
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
} @OneToOne //默认创建的外键名称:husband_id
@JoinColumn(name="husbandId") //创建表时,指定该外键名:husbandId
public Husband getHusband() {
return husband;
}
public void setHusband(Husband husband) {
this.husband = husband;
}
}

1.2、创建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"> <hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property> <mapping class="com.shore.model.Husband" />
<mapping class="com.shore.model.Wife" />
</session-factory>
</hibernate-configuration>

1.3、开始测试

 package com.shore.test;

 import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test; import com.shore.model.Husband;
import com.shore.model.Wife; /**
* @author DSHORE/2019-9-18
*
*/
public class AnnotationTest {
public static SessionFactory sessionFactory = null;
public static Session session = null; @BeforeClass
public static void buildSessionFactory() {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} @AfterClass
public static void close() {
session.close();
sessionFactory.close();
} @Test
public void test(){//数据库表创建完后,插入数据
session = sessionFactory.openSession(); //打开一个session
Transaction transaction = session.beginTransaction(); //开启一个事务
Husband husband = new Husband();
husband.setName("黄晓明");
husband.setSex(true);//男
session.save(husband); Wife wife = new Wife();
wife.setName("AnglaBaby");
wife.setSex(false);//女
wife.setHusband(husband);
session.save(wife);
transaction.commit(); //事务提交
}
}

测试结果图:

    

2、XML实现 版

2.1、创建husband类和wife类

 package com.shore.model;

 /**
* @author DSHORE/2019-9-18
* 一对一,双向关联(xml版)
*/
public class Husband {//主表 类
private Integer id;
private String name;
private Boolean sex;
private Wife wife; public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
}

wife类

 package com.shore.model;

 /**
* @author DSHORE/2019-9-18
* 一对一,双向关联(xml版)
*/
public class Wife {//从表 类
private Integer id;
private String name;
private Boolean sex;
private Husband husband; public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public Husband getHusband() {
return husband;
}
public void setHusband(Husband husband) {
this.husband = husband;
}
}

2.2、创建 Husband.hbm.xml 配置文件和 Wife.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="com.shore.model">
<class name="Husband" table="husband_xml">
<id name="id">
<generator class="native"/>
</id>
<property name="name" type="java.lang.String"/>
<property name="sex" type="yes_no"/> <!-- 这里不能这么配置,否则主表husband里面会多一个没必要的外键wife_id
<many-to-one name="wife" column="wife_id" unique="true"/> --> <!-- 应该这样配置 -->
<one-to-one name="wife" property-ref="husband"/>
</class>
</hibernate-mapping>

Wife.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="com.shore.model">
<class name="Wife" table="wife_xml">
<id name="id">
<generator class="native"/>
</id>
<property name="name" type="java.lang.String"/>
<property name="sex" type="yes_no" /> <!-- many-to-one:多对一,但加了个unique="true",就变成了一对一 -->
<many-to-one name="husband" column="husband_id" unique="true"/>
</class>
</hibernate-mapping>

2.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"> <hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property> <!-- <mapping class="com.shore.model.Husband" />
<mapping class="com.shore.model.Wife" /> -->
<mapping resource="com/shore/model/Husband.hbm.xml" />
<mapping resource="com/shore/model/Wife.hbm.xml" />
</session-factory>
</hibernate-configuration>

2.4、开始测试

 package com.shore.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.shore.model.Husband;
import com.shore.model.Wife; /**
* @author DSHORE/2019-9-19
*
*/
public class XMLTest {
public static SessionFactory sessionFactory = null;
public static Session session = null; @BeforeClass
public static void buildSessionFactory() {
//用注解版的话,Configuration()方法,得改用AnnotationConfiguration()方法
sessionFactory = new Configuration().configure().buildSessionFactory();
} @AfterClass
public static void close() {
session.close();
sessionFactory.close();
} @Test
public void test(){//数据库表创建完后,插入数据
session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Husband husband = new Husband();
husband.setName("黄晓明");
husband.setSex(true);//男
session.save(husband); Wife wife = new Wife();
wife.setName("AnglaBaby");
wife.setSex(false);//女
wife.setHusband(husband);
session.save(wife);
transaction.commit();//事务提交
}
}

测试结果图:

    

Hibernate一对一单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11545058.html
Hibernate一对一双向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11545077.html

Hibernate多对一单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11553213.html
Hibernate一对多单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11553215.html
Hibernate一对多和多对一双向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11560433.html

Hibernate多对多单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11568536.html
Hibernate多对多双向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11568963.html

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/11545077.html

版权声明:欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

Java进阶知识07 Hibernate一对一双向外键关联(Annotation+XML实现)的更多相关文章

  1. Java进阶知识06 Hibernate一对一单向外键关联(Annotation+XML实现)

    1.Annotation 注解版 1.1.创建Husband类和Wife类 package com.shore.model; import javax.persistence.Entity; impo ...

  2. hibernate一对一双向外键关联

    一对一双向外键关联:双方都持有对方的外键关联关系. 主控方和一对一单向外键关联的情况是一样的,主要的差异表现为,被空方需要添加: @OneToOne(mappedBy="card" ...

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

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

  4. 04-hibernate注解-一对一双向外键关联

    一对一双向外键 1,主控方的配置同一对一单向外键关联. 2,@OneToOne(mappedBy="card") //被控方 @OneToOne(mappedBy="ca ...

  5. Hibernate一对一单向外键关联

    一.一对一单向外键关联: 一对一单向外键关联主要用到了以下两个注解: 1.OneToOne(cascade=CasecadeTYPE.ALL); cascade=CasecadeTYPE.ALL:表示 ...

  6. Hibernate 再接触 关系映射 一对一双向外键关联

    凡是双向关联必设mapped by  由对方主导 wifi.java package com.bjsxt.hibernate; import javax.persistence.Entity; imp ...

  7. Hibernate关系映射 一对一双向外键关联@OneToOne Annotation方式 双向关联和单向关联的区别

    首先还是来构造一个实际应用的场景,比如实体类车辆(Car),它具有以下属性:Id,品牌(brand),车牌(lisencePlate):实体类车牌(LisencePlate),它具有以下属性:Id,号 ...

  8. Hibernate关系映射 一对一双向外键关联@OneToOne Annotation方式

    首先还是来构造一个实际应用的场景,比如实体类车辆(Car),它具有以下属性:Id,品牌(brand),车牌(lisencePlate):实体类车牌(LisencePlate),它具有以下属性:Id,号 ...

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

    ²  两个对象之间是一对一的关系,如Person-IdCard(人—身份证号) ²  有两种策略可以实现一对一的关联映射 主键关联:即让两个对象具有相同的主键值,以表明它们之间的一一对应的关系:数据库 ...

随机推荐

  1. ci框架读取上传的excel文件数据

    原文链接: https://blog.csdn.net/qq_38148394/article/details/87921373 此功能实现使用到PHPExcel类库,PHPExcel是一个PHP类库 ...

  2. css多种方式实现等宽布局

    本文讲的等宽布局是在不手动设置元素宽度的情况下,使用纯css实现各个元素宽度都相当的效果. 1.使用table-cell实现(兼容ie8) <style> body,div{ margin ...

  3. 可取消可报告进度的Task

    using System; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace ...

  4. 交替方向乘子法(ADMM)的原理和流程的白话总结

    交替方向乘子法(ADMM)的原理和流程的白话总结 2018年08月27日 14:26:42 qauchangqingwei 阅读数 19925更多 分类专栏: 图像处理   作者:大大大的v链接:ht ...

  5. [多平台]pymo – 手机上的 GalGame 引擎

    [多平台]pymo – 手机上的 GalGame 引擎 介绍下这个能在手机上玩移植 GalGame 的游戏引擎,不知道有多少人听过呢?相信如果有喜欢在手机上玩 GalGame 的同学肯定听过类似的东西 ...

  6. vue防重复点击(指令实现)

    快速点击按钮会重复多次调用接口,防止出现这样的情况 全局定义,方便调用 新建plugins.js export default { install (Vue) { // 防重复点击(指令实现) Vue ...

  7. 5、SVN 权限管理

    5.SVN 权限管理 5.1版本库中三个对应的配置文件 版本库配置文件目录 /var/svn/repository/pro_oa/conf svnserve.conf 文件,如下修改: 19# ano ...

  8. oracle中行转列操作

    数据准备阶段: CREATE TABLE CC  (Student NVARCHAR2(2),Course NVARCHAR2(2),Score INT); INSERT into CC   sele ...

  9. MySql学习笔记【三、表相关操作】

    创建表 CREATE TABLE [IF NOT EXISTS] table_name( column_name data_type, ... ) 如: CREATE TABLE test_table ...

  10. 【Day1】4.基础语法及分支结构

     视频地址(全部) https://edu.csdn.net/course/detail/26057 课件地址(全部) https://download.csdn.net/download/gentl ...