一对一外键关联其实就是多对多特例。
person.java
package com.zzn.hibernate.OneToOne;
public class Person {
private int id;
private String name;
private int age;
private IdCard idCard;
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
IdCard.java
package com.zzn.hibernate.OneToOne;
public class IdCard {
private int id;
private String cardNo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
}
Person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.zzn.hibernate.OneToOne.Person" table="PERSON">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" />
<property name="age" />
<!-- 也就是在person表中加入一个外键idCard,设置unique="ture"就变成一对一了;
cascade="all"必须加上这样两表才能关联,操作person时,Idcard也随之改变-->
<many-to-one name="idCard" unique="true" cascade="all"/>
</class>
</hibernate-mapping>
IdCard.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.zzn.hibernate.OneToOne.IdCard" table="ID_CARD">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="cardNo" />
</class>
</hibernate-mapping>
test.java
public class OneToOne_pk2 extends TestCase {
public void OneToOne_pk2_1() {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
IdCard idCard = new IdCard();
Person person = new Person();
idCard.setCardNo("222222");
person.setName("刘德华");
person.setAge(50);
person.setIdCard(idCard);
session.save(person);
System.out.println("person's name = " + person.getName());
System.out.println("idCard's cardNo = "
+ person.getIdCard().getCardNo());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
if (session.isOpen()) {
tx.commit();
session.close();
}
}
}
}
public void OneToOne_pk2_2() {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
for (int i=1 ;i<=2;i++){
Person person = (Person)session.load(Person.class, i);
System.out.println("person's name = " + person.getName());
System.out.println("idCard's cardNo = "
+ person.getIdCard().getCardNo());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
if (session.isOpen()) {
tx.commit();
session.close();
}
}
}
}
}