对于没有外键关系的简单表,hbm文件中不要做修改就能映射成dom4j的Element,默认每个属性都映射为一个node;有外键关系的要在many-to-one中加入 embed-xml="false",要不的话经常会造成堆栈溢出或者dom4j试图给一个节点设置多个父节点.
简单测试:
<?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="test">
 
 <class name="Xml" table="xml" lazy="true" node="xml">
  <id name="id" column="id" type="long" node="@id">
   <generator class="native"/>
  </id>
  <property name="name" column="name" not-null="true" length="250" node="@name"/>
  
  <bag name="subs" table="sub" inverse="true" node="subs">
   <key column="parent" />
   <one-to-many class="Sub" node="sub"/>
  </bag>
 </class>
 
</hibernate-mapping>
 
<?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="test">
 
 <class name="Sub" table="sub" lazy="true" node="sub">
  <id name="id" column="id" type="long" node="@id">
   <generator class="native"/>
  </id>
  <property name="name" column="name" not-null="true" length="250" node="@name"/>
  
  <many-to-one name="parent" column="parent" class="Xml" embed-xml="false"/>
 </class>
 
</hibernate-mapping>
 
复杂一点的:
<?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="test">
 <class name="Dir" table="dir" lazy="true">
  <id name="id" column="id" type="long" node="@id">
   <generator class="native"/>
  </id>
  <property name="name" column="name" not-null="true" length="50" node="@name"/>
  
  <many-to-one name="parent" column="parent_id" class="Dir" node="@parentId" embed-xml="false"/>
  
  <bag name="children" inverse="true" cascade="all" node="dirs">
   <key column="parent_id"/>
   <one-to-many class="Dir"/>
  </bag>
  
  <bag name="files" inverse="true" table="file" node="files">
   <key column="parent_id" />
   <one-to-many class="File"/>
  </bag>
  
 </class>
 
</hibernate-mapping>
 
<?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="test">
 
 <class name="File" table="file" lazy="true">
  <id name="id" column="id" type="long" node="@id">
   <generator class="native"/>
  </id>
  <property name="title" column="title" not-null="true" length="250"/>
  <property name="content" column="content" not-null="true" type="string"
   lazy="true" length="10000"/>
  <many-to-one name="parent" column="parent_id" class="Dir" not-null="true" node="@parentId" embed-xml="false"/>
 </class>
 
</hibernate-mapping>
 

文章来源:http://spaces.msn.com/members/zzzhc/Blog/cns!1pPbKg7hHgS7AKKQm6CWG1ZQ!124.entry