昨天学习了一对一的单向映射,在这里回顾一下。
首先明确一对一的关联关系正如人和身份证直接的关系一样,一个人只能对应一张身份证;在这里只是从人能看到他的身份证,也就是单向映射。
所以就写了两个实体类,一个是person,另外一个就是IdCard。
person.java文件:
package com.mp.hibernate;
public class Person {
private int id;
private String name;
private 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;
}
}
IdCard.java文件:
package com.mp.hibernate;
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" 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="com.mp.hibernate.Person" table="t_person"> <id name="id"> <generator class="foreign"> <param name="property">idCard</param> </generator> </id> <property name="name"></property> <one-to-one name="idCard" constrained="true"></one-to-one> </class> </hibernate-mapping>
其中
<id name="id">
<generator class="foreign">
<param name="property">idCard</param>
</generator>
</id>
这段完成的是person与Idcard的主键id的关联,当生成一个person时,id从idcard中寻找。
<one-to-one name="idCard" constrained="true"></one-to-one>
<one-to-one>这个标签找的就是一对一关联的对象,里面的constrained设置为true就是 在生成sql语句的时候添加主键约束
写的测试类:
package com.mp.hibernate;
import org.hibernate.Session;
import junit.framework.TestCase;
public class One2OneTest extends TestCase {
public void testSave1() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
IdCard idCard = new IdCard();
idCard.setCardNo("234589389894893384");
Person person = new Person();
person.setName("刘德华");
person.setIdCard(idCard);
//不会出现TransientObejectException异常
//因为一对一主键关联映射中,默认了cascade属性
session.save(person);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateUtils.closeSession(session);
}
}
public void testLoad() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
Person person = (Person)session.load(Person.class, 1);
System.out.println("person.name=" + person.getName());
System.out.println("idcard.cardNo" + person.getIdCard().getCardNo());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateUtils.closeSession(session);
}
}
}
工程文件包含在附件中