2008年6月29日 星期日

[Hibernate] hibernate one-to-one mapping

資料表
ObjA{
column:id,name
PK:id
}


ObjB{
column:ref_obja_id,name
PK:ref_obja_id
FK:ref_obja_id
}


DAO資料模型
package eg;
public class ObjA{
private Integer Id;
private String Name;
private ObjB ObjB;
/*
getter and setter 省略
*/
}


package eg;
public class ObjB{
private Integer RefObjAId;
private String Name;
private ObjA RefObjA;
/*
getter and setter 省略
*/
}



hibernte mapping檔案
ObjA.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 package="eg">
<class name="ObjA" table="ObjA">
<id column="id" name="Id" type="integer">
<generator class="native">
</id>
<property column="name" length="50"
name="Name" type="string"/>
<one-to-one name="ObjB"
class="ObjB"
cascade="all"
/>
</class>
</hibernate-mapping>
}


ObjB.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 package="eg">
<class name="ObjB" table="ObjB">
<id column="ref_obja_id" name="RefObjAId" type="integer">
<generator class="foreign">
<param name="property">RefObjA</param>
</generator>
</id>
<property column="name" generated="never" length="50"
name="Name" type="string"/>
<one-to-one name="RefObjA"
class="ObjA"
constrained="true"
/>
</class>
</hibernate-mapping>
}

沒有留言: