注意! 1 mapping里的name 和 类中的变量名应该是一样的!
2 两个id应该都是一个类型的 比如我的都是String类型的 否则会报错
<?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 >
<class name="hibernate.belle.IDcard" table="t_ID">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
<?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 >
<class name="hibernate.belle.Person" table="t_person">
<id name="id">
<generator class="foreign">
<param name="property">idcard</param>
</generator>
</id>
<property name="name"/>
<one-to-one name="idcard" constrained="true" />
</class>
</hibernate-mapping>
package hibernate.belle;
public class IDcard {
private String no;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
}
package hibernate.belle;
public class Person {
private String id;
private String name;
private IDcard idcard;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public IDcard getIdcard() {
return idcard;
}
public void setIdcard(IDcard idcard) {
this.idcard = idcard;
}
}
主键关联不需要额外的表字段;如果两行是通过这种一对一关系相关联的,那么这两行就共享同样的主关键字值。所以如果你希望两个对象通过主键一对一关联,你必须确认它们被赋予同样的标识值!比如说,对下面的Employee和Person进行主键一对一关联:
<one-to-one name="person" class="Person"/>
<one-to-one name="employee" class="Employee" constrained="true"/>
现在我们必须确保PERSON和EMPLOYEE中相关的字段是相等的。我们使用一个被成为foreign的特殊的hibernate标识符生成策略:
<class name="person" table="PERSON">
<id name="id" column="PERSON_ID">
<generator class="foreign">
<param name="property">employee</param>
</generator>
</id>
...
<one-to-one name="employee"
class="Employee"
constrained="true"/>
</class>
一个刚刚保存的Person实例被赋予和该Person的employee属性所指向的Employee实例同样的关键字值。
下面是加载 Person的id参照idcard的id
所以sessio.save(person)就会先把idcard也save了 (区别于manytoone)
Q:为什么要先session.save();再事务commit
A: 因为session save在缓冲池里面 还不是持久化的 要在
事务commit完了之后 才会变成持久化
import org.hibernate.Session;
import hibernate.belle.HibernateUtils;
import hibernate.belle.IDcard;
import hibernate.belle.Person;
import junit.framework.TestCase;
public class OneToOneTest extends TestCase{
public void test2()
{
Session session= null;
try{
session=HibernateUtils.getSession();
session.beginTransaction();
IDcard idcard=new IDcard();
idcard.setNo("1111111");
Person person1=new Person();
person1.setName("Belle");
person1.setIdcard(idcard);
session.save(person1);
session.beginTransaction().commit();
}catch(Exception e)
{
e.printStackTrace();
session.beginTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
}