alter table wife
drop
foreign key FK37AF11D67CB035
drop table if exists husband
drop table if exists wife
create table husband (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table wife (
id integer not null,
name varchar(255),
primary key (id)
)
alter table wife
add index FK37AF11D67CB035 (id),
add constraint FK37AF11D67CB035
foreign key (id)
references husband (id)
实体
Husband
private int id;
private String name;
private Wife wife;
Wife
private int id;
private String name;
private Husband husband;
Husband.hbm.xml
<?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 package="com.hibernate.one2one.bean">
<class name="Husband" table="husband">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<one-to-one name="wife" cascade="all" class="Wife"></one-to-one>
</class>
</hibernate-mapping>
Wife.hbm.xml
<?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 package="com.hibernate.one2one.bean">
<class name="Wife" table="wife">
<id name="id" column="id">
<generator class="foreign">
<param name="property">husband</param>
</generator>
</id>
<property name="name"></property>
<one-to-one name="husband" constrained="true"></one-to-one>
</class>
</hibernate-mapping>
@Test
public void insert(){
Session session=HibernateSessionFactory.getSession();
Transaction transaction=session.beginTransaction();
try {
transaction.begin();
Husband husband=new Husband();
husband.setName("小明");
session.save(husband);
Wife wife=new Wife();
wife.setName("如花");
wife.setHusband(husband);
session.save(wife);
transaction.commit();
} catch (HibernateException e) {
e.printStackTrace();
transaction.rollback();
}
}
示例程序