1:Person类
public class Person {
private int id;
private String name;
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;
}}
IdCard类
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;
}}
2:配置文件
Person的配置文件
<hibernate-mapping >
<class name="com.bjsxt.hibernate.Person" table="t_person">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<many-to-one name="idCard" unique="true"/>
</class>
</hibernate-mapping>
IdCard的配置文件
<hibernate-mapping >
<class name="com.bjsxt.hibernate.IdCard" table="t_idcard">
<id name="id">
<generator class="native"/>
</id>
<property name="cardNo"></property>
</class>
</hibernate-mapping>3:测试程序
//
public void testSave1(){
Session session = null;
try{
session = HibernateUtils.getSession();
session.beginTransaction();
IdCard idCard = new IdCard();
idCard.setCardNo("88888888888888");
Person person = new Person();
person.setIdCard(idCard);
person.setName("aa");
//不能成功保存,因为idCard是Transient状态
session.save(person);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
//首先保存IdCard,再保存Person
public void testSave2(){
Session session = null;
try{
session = HibernateUtils.getSession();
session.beginTransaction();
IdCard idCard = new IdCard();
idCard.setCardNo("88888888888888");
session.save(idCard);
Person person = new Person();
person.setIdCard(idCard);
person.setName("aa");
session.save(person);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
//首先加载Person,再加载IdCard
public void testLoad1(){
Session session = null;
try{
session = HibernateUtils.getSession();
session.beginTransaction();
Person person = (Person)session.load(Person.class,5);
System.out.println(person.getName());
System.out.println(person.getIdCard().getCardNo());
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
4:总结
hibernate一对一唯一外键关联映射(单向关联Person----->IdCard)
一对一唯一外键关联映射是多对一关联映射的特例
可以采用<many-to-one>标签,指定多的一端的unique=true;这样就限制了多的一端
的多重性为一,通过这种手段映射一对一唯一外键关联