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文件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读