如题目所示,本文讲述的是J2EE中Hibernate xml映射。
对于没有外键关系的简单表,hbm文件中不要做修改就能映射成dom4j的Element,默认每个属性都映射为一个node;有外键关系的要在many-to-one中加入 embed-xml="false",要不的话经常会造成堆栈溢出或者dom4j试图给一个节点设置多个父节点。对Hibernate xml映射映射,可以分简单测试和复杂的测试,如下所示。
简单的测试:
- xml version="1.0"?>
- "-//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"/>
- < SPAN>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"/>
- < SPAN>bag>
- < SPAN>class>
- < SPAN>hibernate-mapping>xml version="1.0"?>
- "-//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"/>
- < SPAN>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"/>
- < SPAN>class>
- < SPAN>hibernate-mapping>
复杂一点的测试:
- xml version="1.0"?>
- "-//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"/>
- < SPAN>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"/>
- < SPAN>bag>
- <bag name="files" inverse="true" table="file" node="files">
- <key column="parent_id" />
- <one-to-many class="File"/>
- < SPAN>bag>
- < SPAN>class>
- < SPAN>hibernate-mapping>xml version="1.0"?>
- "-//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"/>
- < SPAN>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"/>
- < SPAN>class>
- < SPAN>hibernate-mapping>
以上便是Hibernate xml映射映射及其代码。
【编辑推荐】