Hibernate 一对一外键双向关联

本文介绍了一对一外键关联的实现方式,并通过具体的数据库表结构、对象模型、映射文件及测试代码展示了如何在Hibernate中实现这种关联。具体包括创建Person与Address表并设置外键约束,定义Person与Address类之间的关联关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hibernate 一对一外键双向关联
 
一对一外键关联是一对多外键关联的特例,只是在多的一方加了个唯一性约束。
 
一、模型
一个人对应一个地址。
 
/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2008-12-9 0:12:54                            */
/*==============================================================*/

drop table if exists address;
drop table if exists person;
/*==============================================================*/
/* Table: address                                               */
/*==============================================================*/
create table address
(
   id                   bigint not null auto_increment comment 'ID',
   detail               varchar(120) not null comment '详细地址',
   personid             bigint comment '人的ID',
   primary key (id)
)
type = InnoDB;
alter table address comment '地址';
/*==============================================================*/
/* Table: person                                                */
/*==============================================================*/
create table person
(
   id                   bigint not null auto_increment comment 'ID',
   name                 varchar(24) not null comment '姓名',
   primary key (id)
)
type = InnoDB;
alter table person comment '人';
alter table address add constraint FK_Reference_4 foreign key (personid)
      references person (id) on delete restrict on update restrict;
 
 
二、对象模型
 
public class Person implements java.io.Serializable {

  private Long id;
  private String name;
  private Address address;
 
public class Address implements java.io.Serializable {
  private Long id;
  private Person person;
  private String detail;
 
三、映射文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="entity.Person" table="person">
    <id name="id" type="java.lang.Long">
      <column name="id" />
      <generator class="identity" />
    </id>
    <property name="name" type="java.lang.String">
      <column name="name" length="24" not-null="true">
        <comment>姓名</comment>
      </column>
    </property>
    <one-to-one name="address" cascade="all" />
  </class>
</hibernate-mapping>
 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="entity.Address" table="address" catalog="testdb">
    <id name="id" type="java.lang.Long">
      <column name="id" />
      <generator class="identity" />
    </id>
    <property name="detail" type="java.lang.String">
      <column name="detail" length="120" not-null="true">
        <comment>详细地址</comment>
      </column>
    </property>
    <many-to-one name="person" class="entity.Person"
      fetch="select" unique="true">
      <column name="personid">
        <comment>人的ID</comment>
      </column>
    </many-to-one>
  </class>
</hibernate-mapping>
 
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
                    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                                     -->
<hibernate-configuration>

  <session-factory>
    <property name="connection.username">root</property>
    <property name="connection.url">
      jdbc:mysql://localhost:3306/testdb
    </property>
    <property name="dialect">
      org.hibernate.dialect.MySQLDialect
    </property>
    <property name="connection.password">xiaohui</property>
    <property name="connection.driver_class">
      com.mysql.jdbc.Driver
    </property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <mapping resource="entity/Person.hbm.xml" />
    <mapping resource="entity/Address.hbm.xml" />

  </session-factory>

</hibernate-configuration>
 
四、测试
import org.hibernate.Transaction;

import entity.Address;
import entity.Person;

import utils.HibernateSessionFactory;

public class Test {
  public static void main(String[] args) {
    savePerson();
  }

  public static void savePerson() {
    Person person = new Person("张三");
    Address address = new Address("XX街X号");
    person.setAddress(address);
    address.setPerson(person);

    Session session = HibernateSessionFactory.getSession();
    Transaction tx = session.beginTransaction();
    session.save(person);
    tx.commit();
  }
}
 
运行日志:
Hibernate:    
        insert    
        into
                person
                (name)    
        values
                (?)
Hibernate:    
        insert    
        into
                testdb.address
                (detail, personid)    
        values
                (?, ?)
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值