Hibernate关系映射一对一
1. 一对一,比如一个表的字段有100多个,而且其中有40个其他表可能有用,那么你把这个表拆分成两个表,并且两个表中的数据都是一条记录对应一条记录,某一个表中存放另一个对应表的id用来维护两个记录之间的关系,因为本来这两条记录原来就是一条记录,不知道这么说你能明白吗?再比如:人和身份证
2. 身份证IdCard类:
public class IdCard {
private int id;
private Date usefulLife;
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
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;
}
3. 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;
}
4. 映射文件:
IdCard
<hibernate-mapping
package="com.hbsi.domain">
<class name="IdCard" table="id_card">
<id name="id"column="id">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<property name="usefulLife"column="userful_life"/>
<one-to-one name="person"></one-to-one>
</class>
</hibernate-mapping>
Person映射文件
<hibernate-mapping
package="com.hbsi.domain">
<class name="IdCard" table="id_card">
<id name="id"column="id">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<property name="usefulLife"column="userful_life"/>
<one-to-one name="person"></one-to-one>
</class>
</hibernate-mapping>
5.测试类
public static void main(String[] args) {
// TODO Auto-generatedmethod stub
add();
}
static Person add(){
Session s=null;
Transaction tx=null;
try{
s= HibernateUtil.getSession();
tx=s.beginTransaction();
//增加
IdCard idCard=new IdCard();
idCard.setUsefulLife(new Date());
Person p=new Person();
p.setName("ds");
p.setIdCard(idCard);
//
idCard.setPerson(p);
s.save(p);
s.save(idCard);
tx.commit();
return p;
}finally{
if(s!=null)
s.close();
}
}
static Person queryq1(int perId){
Session s=null;
Transaction tx=null;
try{
s= HibernateUtil.getSession();
tx=s.beginTransaction();
Person d= (Person) s.get(Person.class, perId);
System.out.println(d.getName());
tx.commit();
return d;
}finally{
if(s!=null)
s.close();
}
}