如表
第一步:实现Person表和IdCard表的实体类
第二步:
1、进行Person实体类 的配置,如下:
<class name="entity.Person">
<id name="id">
<generator class="sequence">
<param name="sequence">seq_person</param>
</generator>
</id>
<property name="name" />
<one-to-one name="idCard" class="entity.IdCard" />
</class>
2、进行IdCard实体类的配置,如下:
<class name="entity.IdCard">
<id name="id">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<property name="no" />
<one-to-one name="person" class="entity.Person" constrained="true" />
</class>
第三步:使用hibernate.cfg.xml映射其的路径
<mapping resource="entity/IdCard.hbm.xml" />
<mapping resource="entity/Person.hbm.xml" />
第四步:进行数据操作
Session session = HibernateSessionFactory.getSession();
Transaction tx = null;
Person person = new Person("李炎恢");
IdCard idCard = new IdCard("123456");
try {
person.setIdCard(idCard);
idCard.setPerson(person);
tx = session.beginTransaction();
session.save(person);
session.save(idCard);
tx.commit();
System.out.println("保存成功!!!");
} catch (HibernateException e) {
e.printStackTrace();
tx.rollback();
}finally{
HibernateSessionFactory.closeSession();
}
效果图:
查看数据库是否存在该表
selectid, namefrom person;
selectid, nofrom idcard