2008年6月29日 星期日

[Hibernate] hibernate one-to-many mapping

資料表
Parent{
column:id,name
PK:id
}
Child{
column:id,name,ref_parent_id
PK:id
FK:ref_parent_id
}


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


package eg;
public class Child{
private Integer Id;
private String Name;
private Parent RefParent;
/*
getter and setter 省略
*/
}

hibernte mapping檔案
Parent.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="Parent" table="Parent">
<id column="id" name="Id" type="integer">
<generator class="native">
</id>
<property column="name" length="50"
name="Name" type="string"/>
<set cascade="all" inverse="true" name="Children">
<key column="ref_parent_id"><!--重要:Children的FK而不是PK-->
<one-to-many class="Child">
</set>
</class>
</hibernate-mapping>
}


Child.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="Child" table="Child">
<id column="id" name="Id" type="integer">
<generator class="native">
</id>
<property column="name" generated="never" length="50"
name="Name" type="string"/>
<many-to-one class="Parent" column="ref_parent_id" name="RefParent" null="true">
</class>
</hibernate-mapping>
}

實際操作
取得Parnet List,連帶取得Child的Set

//open session lazy=true
Query query = null;
Session hsession = null;
List<Parent> list=null;
int i=0;
query=hsession.createQuery("FROM Parent");//
query.setFirstResult(0);
query.setMaxResults(5);//取5筆
list=query.list();
for(i=0;i<list.size();i++){
out.println("Parent 有 "+list.get(i).getChildren().size()+"個Child");
}
//close session

//取得指定Parent,關閉session,再取得Parent的Children
//open session lazy=true 延遲讀取
Query query = null;
Session hsession = null;
List<Parent> list=null;
int i=0,n=1;
query=hsession.createQuery("FROM Parent p WHERE p.Id=:id");
query.setInteger("id",n);
Parent p =(Parent)query.uniqueResult();
Hibernate.initialize(p.getChildren());
//close session
out.println("Parent 有 "+p.getChildren().size()+"個Child");

沒有留言: