Hibernate双向一对一映射关系配置代码实例
1、外键映射
1.1、实体类
package com.yl.bean; import java.io.Serializable; /** * 公民实体类 */public class Person implements Serializable {private Integer id; private String name; private PersonCard card; public Person() {}public Person(Integer id, String name, PersonCard card) {this.id = id; this.name = name; this.card = card; }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 PersonCard getCard() {return card; }public void setCard(PersonCard card) {this.card = card; }@Overridepublic String toString() {return "Person{" +"id=" + id +", name='" + name + '\'' +", card=" + card +'}'; }}
package com.yl.bean; import java.io.Serializable; /** * 身份证实体类 */public class PersonCard implements Serializable {private Integer id; private String cardNo; private Person person; public PersonCard() {}public PersonCard(Integer id, String cardNo, Person person) {this.id = id; this.cardNo = cardNo; this.person = person; }public Integer getId() {return id; }public void setId(Integer id) {this.id = id; }public String getCardNo() {return cardNo; }public void setCardNo(String cardNo) {this.cardNo = cardNo; }public Person getPerson() {return person; }public void setPerson(Person person) {this.person = person; }@Overridepublic String toString() {return "PersonCard{" +"id=" + id +", cardNo='" + cardNo + '\'' +", person=" + person +'}'; }}
1.2、全局配置文件(hibernate.cfg.xml)
com.mysql.cj.jdbc.Driverjdbc:mysql://localhost:3306/hibernate?characterEncoding=utf8& serverTimezone=GMT%2B8root123456trueupdate
1.3、公民映射配置文件(Person.hbm.xml)
1.4、身份证映射配置文件(PersonCard.hbm.xml)
1.5、测试类
@Testpublic void test01(){Person person=new Person(); person.setName("yl001"); PersonCard personCard=new PersonCard(); personCard.setCardNo("001"); person.setCard(personCard); personCard.setPerson(person); Session session= HibernateUtils.getSession(); Transaction transaction=session.beginTransaction(); session.save(person); session.save(personCard); transaction.commit(); session.close(); }
2、主键映射
表的字段既是主键,又是外键(eg:身份证号码既是主键又是外键)
2.1、映射配置文件实现
【Hibernate双向一对一映射关系配置代码实例】主要修改PersonCard.hbm.xml文件
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
推荐阅读
- 今天,第24次健身一对一
- 直播+社交(一对一社交app源码或成直播平台开发新宠)
- 27|27 二叉搜索树与双向链表
- 如何理解vue数据双向绑定原理
- 乘风破浪的新手妈妈D78
- 1.hibernate入门(hibernate笔记)
- 程序员|vue数据双向绑定,Android-MVP模式详解,附超全教程文档
- Hibernate学习笔记(三)|Hibernate学习笔记(三) 一些概念
- 技术部如何做复盘——“年终盘点一对一”之做大做强再创辉煌
- 王堃阳VIP一对一训练简介《神奇魔法口才公众演说实战特训营》