配置单向一对一关联
如表
第一步:实现Person表和IdCard表的实体类
第二步:
1、进行Person实体类 的配置,如下:
<classname="entity.Person">
<idname="id">
<generatorclass="sequence">
<paramname="sequence">seq_person</param>
</generator>
</id>
<propertyname="name" />
<one-to-onename="idCard" class="entity.IdCard" />
</class>
2、进行IdCard实体类的配置,如下:
<classname="entity.IdCard">
<idname="id">
<generatorclass="foreign">
<paramname="property">person</param>
</generator>
</id>
<propertyname="no" />
<one-to-onename="person" class="entity.Person" constrained="true" />
</class>
第三步:使用hibernate.cfg.xml映射其的路径
<mappingresource="entity/IdCard.hbm.xml" />
<mappingresource="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
标签:Hibernate,tx,Person,一对一,IdCard,person,session,idCard From: https://blog.51cto.com/u_16089934/6228053