一 概念介紹
一對一的方式有兩種,分為:
(1)基於主鍵的方式 --- 共用主鍵(Person --- IdCard)典型的一對一
沒有增加額外的列
(2)基於外鍵的方式 --- 增加額外的一列
下面介紹一下第一中基於主鍵的實現
二 代碼分析
(1)Person類
package com.hbsi.domain;
public class Person {
private int id;
private String name;
private IdCard idCard;//一個人對應一個IdCard
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(int id, String name, IdCard idCard) {
super();
this.id = id;
this.name = name;
this.idCard = idCard;
}
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;
}
public String toString() {
return "Person [id=" + id + ", name=" + name + ", idCard=" + idCard
+ "]";
}
}
(2)IdCard類
package com.hbsi.domain;
import java.util.Date;
public class IdCard {
private int id;
private Date usefulLife;
private Person person; //一個IdCard只屬於一個人
public IdCard() {
super();
// TODO Auto-generated constructor stub
}
public IdCard(int id, Date usefulLife, Person person) {
super();
this.id = id;
this.usefulLife = usefulLife;
this.person = person;
}
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類和IdCard類
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- 配置文件 -->
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///demo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 方言 針對哪個數據庫Mysql -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 在程序運動的時候,增加自動創建表的屬性,在程序終止 的時候銷毀,但是在表格再次使用時,會重新建 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 執行的sql語句顯示出來 -->
<property name="hibernate.show_sql">true</property>
<!-- 指定映射文件的位置 -->
<mapping resource="com/hbsi/domain/Person.hbm.xml" />
<mapping resource="com/hbsi/domain/IdCard.hbm.xml" />
</session-factory>
</hibernate-configuration>