ITeye博客

Hibernate 一对一外键双向关联

sdustyongz · 2011-03-21 11:07 · java 学习 · 企业架构 · Markdown

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;

三、映射文件

四、测试 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 (?, ?)

本文出自 “熔 岩” 博客,转载请与作者联系!

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。