一 概念分析
1.以Person – IdCard为例,Person为主,IdCard为从
一个人只有一个身份证,一个身份证只属于一个人
基于外键的是在从的那一方设置外键并增加一列
二 代码分析
1.Person实例类
package com.hbsi.domain;
public class Person {
private int id;
private String name;
private IdCard idCard; //一个人对应一个身份证
public Person() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int 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;
}
}
2.Student实例类
package com.hbsi.domain;
import java.util.Date;
//基于外键的one to one
public class IdCard {
private int id;
private Date usefulLife;
private Person person;//一个身份证只属于一个人
public IdCard() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getUsefulLife() {
return usefulLife;
}
public void setUsefulLife(Date usefulLife) {
this.usefulLife = usefulLife;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
3.Person的映射文件 Person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hbsi.domain">
<class name="Person" table="person">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<!--property-ref 属性的参照,即参照的是person类中的-->
<one-to-one name="idCard" property-ref="person"></one-to-one>
</class>
</hibernate-mapping>