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. Docker——四种网络模式

    docker run创建Docker容器时,可以用–net选项指定容器的网络模式,Docker有以下4种网络模式:  bridge模式:使用–net =bridge指定,默认设置:  host模式 ...

  2. Jmeter之梯度式加压(Stepping Thread Group)

    1.添加线程组(Stepping Thread Group) 2.设置数据 学习参考网址:https://www.cnblogs.com/imyalost/p/7658816.html   这个大大的 ...

  3. 05docker仓库---搭建本地仓库

    Docker仓库 仓库(Repository)是集中存放镜像的地方,分别公有仓库和私有仓库. 注册服务器是存放仓库的具体服务器.一个注册服务器上可以有多个仓库,每一个仓库里面可以有多个镜像. eg:仓 ...

  4. 国内有哪些好的JAVA社区

    转载自 https://www.zhihu.com/question/29836842#answer-13737722 并发编程网 - ifeve.com 强烈推荐 ImportNew - 专注Jav ...

  5. Spingboot+Mybatis+Oracle项目配置

    配置过程参考: 项目创建:http://how2j.cn/k/springboot/springboot-eclipse/1640.html 集成Mybatis使用Oracle:https://www ...

  6. oracle数据库锁的问题

    查询当前数据库被锁的对象 select b.owner,b.object_name,a.SESSION_ID,a.LOCKED_MODE from v$locked_object a dba_obje ...

  7. day07 类

    一.目录 1.模块 2.包 3.isinstance issubclass type 4.方法和函数 5.反射 6.约束 7.继承 8.特殊成员 9.异常处理 补充知识点 10.hashlib模块 1 ...

  8. redis-cluster集群总结

    Redis集群搭建 要想搭建一个最简单的Redis集群,那么至少需要6个节点:3个Master和3个Slave.为什么需要3个Master呢?如果你了解过Hadoop/Storm/Zookeeper这 ...

  9. deep_learning_Function_ lambda函数详解

    这里总结了关于 Python 中的 lambda 函数的“一个语法,三个特性,四个用法”. 一个语法: 在 Python 中,lambda 函数的语法是唯一的.其形式如下: lambda argume ...

  10. linux 启动tomcat

    操作步骤: 第一步:进入tomcat的bin目录 cd /usr/local/tomcat/bin 第二步:使用tomcat关闭命令 ./shutdown.sh 第三步:查看tomcat是否关闭 ps ...