hibernate onetoone 双向主键映射
程序员文章站
2022-04-22 16:10:21
...
主键关联,就是两个一对一的实体共用相同的id
而唯一外键映射:是通过manytoone unique的方法 增加一个外键字段完成的
onetoone不影响存储 只影响加载
package hibernate.belle;
public class IDcard {
private String no;
private String id;
private Person person;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
package hibernate.belle;
public class Person {
private String id;
private String name;
private IDcard idcard;
public String getId() {
return id;
}
public void setId(String 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;
}
}
配置文件:
<?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="hibernate.belle.IDcard" table="t_idcard">
<id name="id" >
<generator class="native"/>
</id>
<property name="no"/>
<one-to-one name="person"></one-to-one>
</class>
</hibernate-mapping>
<?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="hibernate.belle.Person" table="t_person">
<id name="id">
<generator class="foreign">
<param name="property">idcard</param>
</generator>
</id>
<property name="name"/>
<one-to-one name="idcard" constrained="true" />
</class>
</hibernate-mapping>
测试:
import org.hibernate.Session;
import hibernate.belle.HibernateUtils;
import hibernate.belle.IDcard;
import hibernate.belle.Person;
import junit.framework.TestCase;
public class OneToOneTest extends TestCase{
public void test2()
{
Session session=null;
try{
session=HibernateUtils.getSession();
session.beginTransaction();
IDcard idcard=new IDcard();
idcard.setNo("1112");
Person person=new Person();
person.setName("Belle");
person.setIdcard(idcard);
session.save(person);//双向的时候还是靠person维护 你用idcard.setperson save(idcard) hibernate还是不知道这个关系的 所以还是得要按这样存
/// System.out.println("idd's name is "+idd.getPerson().getName());
session.beginTransaction().commit();
}catch(Exception e)
{
e.printStackTrace();
session.beginTransaction().rollback();
}finally
{
HibernateUtils.closeSession(session);
}
}
public void testload()
{
Session session=null;
try{
session= HibernateUtils.getSession();
session.beginTransaction();
IDcard idd=(IDcard)session.load(IDcard.class,"3");
System.out.println("idd's name is "+idd.getPerson().getName());
session.beginTransaction().commit();
}catch(Exception e)
{
e.printStackTrace();
session.beginTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
}