外键方式:
<class name="com.chenjun.eshop.staffManage.domain.Bed" table="bed">
<id name="id" column="BEDID">
<generator class="assigned"><!-- 由程序分配主键 -->
</generator>
</id>
<property name="sizes">
<column name="sizes"></column>
</property>
<many-to-one name="person" class="com.chenjun.eshop.staffManage.domain.Person" unique="true">
<column name="personID"></column>
</many-to-one>
</class>
<class name="com.chenjun.eshop.staffManage.domain.Person"
table="person">
<id name="id" column="personID">
<generator class="assigned"><!-- 由程序分配主键 -->
</generator>
</id>
<property name="name">
<column name="name" not-null="true" />
</property>
<one-to-one name="bed" cascade="delete,save-update"
class="com.chenjun.eshop.staffManage.domain.Bed"
property-ref="person"><!-- person为Bed里的对象属性 -->
</one-to-one>
</class>
测试代码:
public void test()
{
Bed bed = new Bed();
bed.setId("001008");
bed.setSizes(40);
Person person = new Person();
person.setId("002008");
person.setName("ms chen");
bed.setPerson(person);
person.setBed(bed);
Session session = this.getHibernateTemplate().getSessionFactory().openSession();
session.beginTransaction();
session.save(person);
session.beginTransaction().commit();
session.close();
}
主键方式:
<class name="com.chenjun.eshop.staffManage.domain.Bed" table="bed">
<id name="id" column="BEDID">
<generator class="foreign">
<param name="property">person</param> <!-- bedid字段的值与person对应表的主键值一样,共用主键 -->
</generator>
<!-- <generator class="assigned">由程序分配主键
</generator>-->
</id>
<property name="sizes">
<column name="sizes"></column>
</property>
<one-to-one name="person"></one-to-one>
</class>
<class name="com.chenjun.eshop.staffManage.domain.Person"
table="person">
<id name="id" column="personID">
<generator class="assigned"><!-- 由程序分配主键 -->
</generator>
</id>
<property name="name">
<column name="name" not-null="true" />
</property>
<one-to-one name="bed"></one-to-one>
</class>
测试代码:
public void test()
{
Bed bed = new Bed();
bed.setSizes(40);
Person person = new Person();
person.setId("002009");
person.setName("ms chen");
bed.setPerson(person);
// person.setBed(bed);
Session session = this.getHibernateTemplate().getSessionFactory().openSession();
session.beginTransaction();
session.save(person); //分别保存
session.save(bed);
session.beginTransaction().commit();
session.close();
}