8.1.2 Hibernate:一对一双向关联(bidirectional)

2023-12-16 04:48

本文主要是介绍8.1.2 Hibernate:一对一双向关联(bidirectional),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 定义映射类
1.1 表 phone 的映射类定义:

package hibernate;import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;@Entity
@Table(name = "phone")
public class Phone {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id")private int id;@Column(name = "imei")private String imei;@Column(name = "number")private String number;@OneToOne(mappedBy = "phone", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.EAGER)private PhoneDetail phoneDetail;public Phone() {}public Phone(String imei, String number) {this.imei = imei;this.number = number;}// 省略 Getters 和 Setters ...}

1.2 表 phone_detail 的映射类定义:

package hibernate;import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;@Entity
@Table(name = "phone_detail")
public class PhoneDetail {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id")private int id;@Column(name = "manufacturer")private String manufacturer;@Column(name = "model")private String model;@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)@JoinColumn(name = "phone_id")private Phone phone;public PhoneDetail() {}public PhoneDetail(String manufacturer, String model) {this.manufacturer = manufacturer;this.model = model;}// 省略 Getters 和 Setters ...}

2 测试
2.1 新增

@Test
public void test() {Configuration configuration = new Configuration().configure("hibernate.cfg.xml");SessionFactory sessionFactory = configuration.buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();Phone phone = new Phone("812345678912345", "18012345678");PhoneDetail phoneDetail = new PhoneDetail("XXX", "XXX-2017");phone.setPhoneDetail(phoneDetail);phoneDetail.setPhone(phone);session.save(phone);transaction.commit();session.close();sessionFactory.close();
}

运行测试,数据库表 phonephone_detail 中新插入了两条数据(日志省略)。

将单元测试中 session.save(phone); 替换成 session.save(phoneDetail);,测试结果相同。

由此可见,双向关联的任一方都维护级联关系。

2.2 删除
基于以上测试新增的数据进行删除测试。

@Test
public void test() {Configuration configuration = new Configuration().configure("hibernate.cfg.xml");SessionFactory sessionFactory = configuration.buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();Phone phone = (Phone) session.createQuery(" FROM Phone").list().get(0);session.delete(phone);transaction.commit();session.close();sessionFactory.close();
}

运行测试,数据库表 phonephone_detail 中对应记录被删除(日志省略)。

将单元测试中

Phone phone = (Phone) session.createQuery(" FROM Phone").list().get(0);
session.delete(phone);

替换成

PhoneDetail phoneDetail = (PhoneDetail) session.createQuery(" FROM PhoneDetail").list().get(0);
session.delete(phoneDetail);

测试结果相同。

2.3 更新
基于新增测试的数据进行更新测试。
2.3.1 通过 Phone 查找关联的 PhoneDetail 并执行级联更新

@Test
public void test() {Configuration configuration = new Configuration().configure("hibernate.cfg.xml");SessionFactory sessionFactory = configuration.buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();Phone phone = (Phone) session.createQuery(" FROM Phone").list().get(0);phone.setImei("898765432198765");phone.setNumber("17712345678");PhoneDetail phoneDetail = phone.getPhoneDetail();phoneDetail.setManufacturer("YYY");phoneDetail.setModel("YYY-2017");session.save(phone);transaction.commit();session.close();sessionFactory.close();
}

运行测试,数据库表 phonephone_detail 中对应记录级联更新成功(日志省略)。

将单元测试中 session.save(phone); 替换成 session.save(phoneDetail);,测试结果相同,同样级联更新成功。

2.3.1 通过 PhoneDetail 查找关联的 Phone 并执行级联更新

@Test
public void test() {Configuration configuration = new Configuration().configure("hibernate.cfg.xml");SessionFactory sessionFactory = configuration.buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();PhoneDetail phoneDetail = (PhoneDetail) session.createQuery(" FROM PhoneDetail").list().get(0);phoneDetail.setManufacturer("YYY");phoneDetail.setModel("YYY-2017");Phone phone = phoneDetail.getPhone();phone.setImei("898765432198765");phone.setNumber("17712345678");session.save(phoneDetail);transaction.commit();session.close();sessionFactory.close();
}

运行测试,数据库表 phonephone_detail 中对应记录级联更新成功(日志省略)。

将单元测试中 session.save(phoneDetail); 替换成 session.save(phone);,测试结果相同,同样级联更新成功。

2.4 查询
基于新增测试的数据进行查询测试。

@Test
public void test() {Configuration configuration = new Configuration().configure("hibernate.cfg.xml");SessionFactory sessionFactory = configuration.buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();Phone phone = (Phone) session.createQuery(" FROM Phone").list().get(0);System.out.println("-------------------- From Phone --------------------");System.out.println("Phone ID : " + phone.getId());System.out.println("Phone IMEI : " + phone.getImei());System.out.println("Phone Number : " + phone.getNumber());System.out.println("Binded Phone Detail ID : " + phone.getPhoneDetail().getId());System.out.println("Binded Phone Detail Manufacture : " + phone.getPhoneDetail().getManufacturer());System.out.println("Binded Phone Detail Model : " + phone.getPhoneDetail().getModel());System.out.println("----------------------------------------------");PhoneDetail phoneDetail = (PhoneDetail) session.createQuery(" FROM PhoneDetail").list().get(0);System.out.println("-------------------- From Phone Detail --------------------");System.out.println("Phone Detail ID : " + phoneDetail.getId());System.out.println("Phone Detail Manufacture : " + phoneDetail.getManufacturer());System.out.println("Phone Detail Model : " + phoneDetail.getModel());System.out.println("Binded Phone ID : " + phoneDetail.getPhone().getId());System.out.println("Binded Phone IMEI : " + phoneDetail.getPhone().getImei());System.out.println("Binded Phone Number : " + phoneDetail.getPhone().getNumber());System.out.println("----------------------------------------------");transaction.commit();session.close();sessionFactory.close();
}

运行测试,打印结果:

......
-------------------- From Phone --------------------
Phone ID : 15
Phone IMEI : 898765432198765
Phone Number : 17712345678
Binded Phone Detail ID : 11
Binded Phone Detail Manufacture : YYY
Binded Phone Detail Model : YYY-2017
----------------------------------------------
......
-------------------- From Phone Detail --------------------
Phone Detail ID : 11
Phone Detail Manufacture : YYY
Phone Detail Model : YYY-2017
Binded Phone ID : 15
Binded Phone IMEI : 898765432198765
Binded Phone Number : 17712345678
----------------------------------------------
......

这篇关于8.1.2 Hibernate:一对一双向关联(bidirectional)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/499152

相关文章

csu1329(双向链表)

题意:给n个盒子,编号为1到n,四个操作:1、将x盒子移到y的左边;2、将x盒子移到y的右边;3、交换x和y盒子的位置;4、将所有的盒子反过来放。 思路分析:用双向链表解决。每个操作的时间复杂度为O(1),用数组来模拟链表,下面的代码是参考刘老师的标程写的。 代码如下: #include<iostream>#include<algorithm>#include<stdio.h>#

java面试常见问题之Hibernate总结

1  Hibernate的检索方式 Ø  导航对象图检索(根据已经加载的对象,导航到其他对象。) Ø  OID检索(按照对象的OID来检索对象。) Ø  HQL检索(使用面向对象的HQL查询语言。) Ø  QBC检索(使用QBC(Qurey By Criteria)API来检索对象。 QBC/QBE离线/在线) Ø  本地SQL检索(使用本地数据库的SQL查询语句。) 包括Hibern

org.hibernate.hql.ast.QuerySyntaxException:is not mapped 异常总结

org.hibernate.hql.ast.QuerySyntaxException: User is not mapped [select u from User u where u.userName=:userName and u.password=:password] 上面的异常的抛出主要有几个方面:1、最容易想到的,就是你的from是实体类而不是表名,这个应该大家都知道,注意

Caused by: org.hibernate.MappingException: Could not determine type for: org.cgh.ssh.pojo.GoodsType,

MappingException:这个主要是类映射上的异常,Could not determine type for: org.cgh.ssh.pojo.GoodsType,这句话表示GoodsType这个类没有被映射到

Hibernate框架中,使用JDBC语法

/*** 调用存储过程* * @param PRONAME* @return*/public CallableStatement citePro(final String PRONAME){Session session = getCurrentSession();CallableStatement pro = session.doReturningWork(new ReturningWork<C

hibernate修改数据库已有的对象【简化操作】

陈科肇 直接上代码: /*** 更新新的数据并并未修改旧的数据* @param oldEntity 数据库存在的实体* @param newEntity 更改后的实体* @throws IllegalAccessException * @throws IllegalArgumentException */public void updateNew(T oldEntity,T newEntity

react笔记 8-19 事件对象、获取dom元素、双向绑定

1、事件对象event 通过事件的event对象获取它的dom元素 run=(event)=>{event.target.style="background:yellowgreen" //event的父级为他本身event.target.getAttribute("aid") //这样便获取到了它的自定义属性aid}render() {return (<div><h2>{

C++ STL关联容器Set与集合论入门

1. 简介 Set(集合)属于关联式容器,也是STL中最实用的容器,关联式容器依据特定的排序准则,自动为其元素排序。Set集合的底层使用一颗红黑树,其属于一种非线性的数据结构,每一次插入数据都会自动进行排序,注意,不是需要排序时再排序,而是每一次插入数据的时候其都会自动进行排序。因此,Set中的元素总是顺序的。 Set的性质有:数据自动进行排序且数据唯一,是一种集合元素,允许进行数学上的集合相

关联规则(一)Apriori算法

此篇文章转自 http://blog.sina.com.cn/s/blog_6a17628d0100v83b.html 个人觉得比课本上讲的更通俗易懂! 1.  挖掘关联规则 1.1   什么是关联规则 一言蔽之,关联规则是形如X→Y的蕴涵式,表示通过X可以推导“得到”Y,其中X和Y分别称为关联规则的先导(antecedent或left-hand-side, LHS)和后

Hibernate插入数据时,报错:org.springframework.dao.DataIntegrityViolationException: could not insert: [cn.itc

在用junit测试:插入数据时,报一下错误: 错误原因: package junit;import org.junit.Test;import cn.itcast.crm.container.ServiceProvinder;import cn.itcast.crm.dao.ISysUserDao;import cn.itcast.crm.domain.SysRole;