前面的《eclipse快速上手hibernate–1. 入门实例 》等三篇文章已经谈了hibernate的入门以及利用工具创建的方法。这篇文章主要说说在hibernate中的继承映射。相关配置请参考前三篇文章。 如果程序中的对象含有继承的关系,在hibernate中有以下三种策略将这种关系映射到数据表上:· 每个类层次结构一个表(table per class hierarchy)· 每个子类一个表(table per subclass) · 每个具体类一个表(table per concrete class)(有一些限制) 每个类层次结构一个表的方式是将所有继承同一父类别的对象储存在同一个表格中,为了做到这一点,需要在表格中使用识别字段来表示某一列(row)是属于某个子类别或父类别,在这个主题中我们将先说明这个方法。 1. 创建项目 · 新建一个java项目:inheritancemapping,注意选中“创建单独的源文件夹和输出文件夹”,同时添加“用户库”:hibernate。 2. 编写类文件 · 新建一个类,包名:javamxj.inheritance.one,类名:animal。然后在生成的代码中添加变量,再利用“生成 getter 和 setter”,具体方式同《eclipse快速上手hibernate–1. 入门实例 》文章中的编辑user.java的方式一样。
animal.java
/* * hibernate – 继承映射(每个类层次一个表) * 创建日期 2005-4-9 * @author javamxj(分享java快乐) * @link blog: htpp://javamxj.mblogger.cn * htpp://blog.csdn.net/javamxj/ */package javamxj.inheritance.one;/** * @hibernate.class * table="animal" * discriminator-value="animal" * @hibernate.discriminator * column="animal_type" * type="string" * length = "10" */public abstract class animal { private long id; private string name; /** * @hibernate.id * column="id" * generator-class="hilo" * unsaved-value="null" */ public long getid() { return id; } public void setid(long id) { this.id = id; } /** * @hibernate.property * length = "24" */ public string getname() { return name; } public void setname(string name) { this.name = name; } public abstract void makesound();}
· 这个类是父类,值得注意是在类层次标记中添加了一个discriminator标记,并用它定义了一个字段“animal_type”,这个字段就是用来识别某一列(row)是属于某个子类别或父类别的。 · 子类cat.javacat.java
package javamxj.inheritance.one;/** * @hibernate.subclass * discriminator-value="cat" */public class cat extends animal { private string furcolor; public void makesound() { system.out.println("喵喵"); } /** * @hibernate.property * length = "24" */ public string getfurcolor() { return furcolor; } public void setfurcolor(string furcolor) { furcolor = furcolor; }}
· 子类dog.javadog.java
package javamxj.inheritance.one;/** * @hibernate.subclass * discriminator-value="dog" */public class dog extends animal { private string category; public void makesound() { system.out.println("汪汪"); } /** * @hibernate.property * length = "24" */ public string getcategory() { return category; } public void setcategory(string category) { this.category = category; }}
· 这两个子类都很简单,注意添加的hibernate.subclass的标记,指定其识别字段。 3. 构建文件build.xml · 在项目根目录下建立一个build.xml,要注意的是环境变量和数据库的设置要符合自己的实际配置,这里库文件目录的设置是"d:/java/hibernate/lib",参考文章《eclipse快速上手hibernate–1. 入门实例》中的设置。· 在mysql中需要先建立一个hibernatetest数据库,为了解决中文问题,使用了gbk编码,注意“&”,这是由于xdoclet生成hibernate配置文件时,会丢失一个“amp;”字符串(一个小bug)。· 这里我用build.xml中的“hibernatedoclet”任务直接生成“hibernate.cfg.xml”配置文件。
build.xml
<?xml version="1.0" encoding="gbk"?><project name="hibernate中的继承映射" default="help" basedir="."> <!– ****** 环境设置,可以根据自己的实际配置自行更改 ***** –> <!– 源文件目录, 可以通过 项目->属性->java构建路径 更改 –> <property name="src.dir" value="./src" /> <!– 输出的class文件目录,可以通过 项目->属性->java构建路径 更改 –> <property name="class.dir" value="./bin" /> <!– 库文件目录 –> <property name="lib.dir" value="d:/java/hibernate/lib" /> <!– ****** 数据库设置,可以根据自己的实际配置自行更改 ***** –> <property name="hibernate.dialect" value="net.sf.hibernate.dialect.mysqldialect"></property> <property name="hibernate.driver" value="com.mysql.jdbc.driver"></property> <!– &amp; –> <property name="hibernate.jdbc.url" value="jdbc:mysql://localhost:3306/hibernatetest?useunicode=true&amp;characterencoding=gbk"> </property> <property name="hibernate.username" value="root"></property> <property name="hibernate.password" value="javamxj"></property> <property name="hibernate.show.sql" value="true"></property> <!– 定义类路径 –> <path id="project.class.path"> <fileset dir="${lib.dir}"> <include name="*.jar"/> </fileset> <pathelement location="${class.dir}" /> </path> <!– ************************************************************** –> <!– 使用说明 –> <!– ************************************************************** –> <target name="help"> <echo message="利用工具开发hibernate" /> <echo message="———————————–" /> <echo message="" /> <echo message="提供以下任务:" /> <echo message="" /> <echo message="generate-hbm –> 运行hibernatedoclet,生成 hibernate 类的映射文件" /> <echo message="schemaexportt –> 运行schemaexport,利用 hbm.xml 文件生成数据表" /> <echo message="" /> </target> <!– ************************************************************** –> <!– hibernatedoclet 任务 –> <!– ************************************************************** –> <target name="generate-hbm" > <echo message="运行hibernatedoclet,生成 hibernate 类的映射文件"/> <taskdef name="hibernatedoclet" classname="xdoclet.modules.hibernate.hibernatedoclettask" classpathref="project.class.path"> </taskdef> <hibernatedoclet destdir="${src.dir}" excludedtags="@version,@author,@todo" force="true" encoding="gbk" verbose="true"> <fileset dir="${src.dir}"> <include name="**/*.java"/> </fileset> <hibernate version="2.0" xmlencoding="gbk" /> <!– 生成配置文件 –> <hibernatecfg dialect="${hibernate.dialect}" driver="${hibernate.driver}" jdbcurl="${hibernate.jdbc.url}" username="${hibernate.username}" password="${hibernate.password}" showsql="${hibernate.show.sql}" xmlencoding="gbk" /> </hibernatedoclet> </target> <!– ************************************************************** –> <!– schemaexport 任务 –> <!– ************************************************************** –> <target name="schemaexport"> <echo message="运行schemaexport,利用 hbm.xml 文件生成数据表"/> <taskdef name="schemaexport" classname="net.sf.hibernate.tool.hbm2ddl.schemaexporttask" classpathref="project.class.path"> </taskdef> <schemaexport config="${src.dir}/hibernate.cfg.xml" quiet="no" text="no" drop="no" output="schema-export.sql"> </schemaexport> </target></project>
· 好了,只要这四个文件就够了,其它的会自动生成的。整个项目的结构如下: 4. 运行任务 · 双击“generate-hbm”任务,会发现在包中多了一个animal.hbm.xml文件,在src目录下会多了一个hibernate.cfg.xml文件,如果没有,按f5键刷新一下(这里建议打开eclipse的“首选项”对话框,在“工作台”中勾选“自动刷新工作空间”和“在构建之前自动保存”这两项,这样以后不用每次都刷新了)。
animal.hbm.xml
<?xml version="1.0" encoding="gbk"?><!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 2.0//en" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping> <class name="javamxj.inheritance.one.animal" table="animal" dynamic-update="false" dynamic-insert="false" select-before-update="false" optimistic-lock="version" discriminator-value="animal" > <id name="id" column="id" type="java.lang.long" unsaved-value="null" > <generator class="hilo"> <!– to add non xdoclet generator parameters, create a file named hibernate-generator-params-animal.xml containing the additional parameters and place it in your merge dir. –> </generator> </id> <discriminator column="animal_type" type="string" length="10" /> <property name="name" type="java.lang.string" update="true" insert="true" access="property" column="name" length="24" /> <!– to add non xdoclet property mappings, create a file named hibernate-properties-animal.xml containing the additional properties and place it in your merge dir. –> <subclass name="javamxj.inheritance.one.cat" dynamic-update="false" dynamic-insert="false" discriminator-value="cat" > <property name="furcolor" type="java.lang.string" update="true" insert="true" access="property" column="furcolor" length="24" /> <!– to add non xdoclet property mappings, create a file named hibernate-properties-cat.xml containing the additional properties and place it in your merge dir. –> </subclass> <subclass name="javamxj.inheritance.one.dog" dynamic-update="false" dynamic-insert="false" discriminator-value="dog" > <property name="category" type="java.lang.string" update="true" insert="true" access="property" column="category" length="24" /> <!– to add non xdoclet property mappings, create a file named hibernate-properties-dog.xml containing the additional properties and place it in your merge dir. –> </subclass> </class></hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="gbk"?><!doctype hibernate-configuration public "-//hibernate/hibernate configuration dtd 2.0//en" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"><!– generated file – do not edit! –><hibernate-configuration> <!– a sessionfactory instance listed as /jndi/name –> <session-factory> <!– properties –> <property name="dialect">net.sf.hibernate.dialect.mysqldialect</property> <property name="show_sql">true</property> <property name="use_outer_join">false</property> <property name="connection.username">root</property> <property name="connection.password">javamxj</property> <property name="connection.driver_class">com.mysql.jdbc.driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernatetest?useunicode=true&characterencoding=gbk</property> <!– mapping files –> <mapping resource="javamxj/inheritance/one/animal.hbm.xml"/> </session-factory></hibernate-configuration>
· 双击“schemaexport”任务,在项目根目录下,会产生一个“schema-export.sql”文件。schema-export.sqldrop table if exists animaldrop table if exists hibernate_unique_keycreate table animal ( id bigint not null, animal_type varchar(10) not null, name varchar(24), furcolor varchar(24), category varchar(24), primary key (id))create table hibernate_unique_key ( next_hi integer )insert into hibernate_unique_key values ( 0 ) · 切换到数据库中,会发现已经自动产生了数据表animal(表hibernate_unique_key是由于采用hilo主键策略生成的)。 5. 测试程序 · 好了,在包javamxj.inheritance.one下新建一个demo.java类,很简单,前半部分是添加数据,后半部分是简单的测试。
demo.java
package javamxj.inheritance.one;import java.util.iterator;import java.util.list;import net.sf.hibernate.hibernateexception;import net.sf.hibernate.session;import net.sf.hibernate.sessionfactory;import net.sf.hibernate.transaction;import net.sf.hibernate.cfg.configuration;public class demo { public static void main(string[] args) { try { new demo(); } catch (hibernateexception he) { he.printstacktrace(); } } public demo() throws hibernateexception { sessionfactory sf = new configuration().configure() .buildsessionfactory(); session sess = sf.opensession(); transaction tx = null; try { tx = sess.begintransaction(); cat cat = new cat(); cat.setname("小白"); cat.setfurcolor("白色"); sess.save(cat); dog dog = new dog(); dog.setname("小黑"); dog.setcategory("京巴狗"); sess.save(dog); tx.commit(); } catch (hibernateexception e) { if (tx != null) tx.rollback(); throw e; } finally { sess.close(); } sess = sf.opensession(); tx = null; try { tx = sess.begintransaction(); list animals = sess.find("from " + animal.class.getname()); for (iterator it = animals.iterator(); it.hasnext();) { animal animal = (animal) it.next(); system.out.println("动物 " + animal.getname() + " 所在类是: " + animal.getclass().getname()); system.out.print("发出叫声: "); animal.makesound(); } tx.commit(); } catch (hibernateexception e) { if (tx != null) tx.rollback(); throw e; } finally { sess.close(); } }}
· 运行这个类,控制台输出如下: · 同时,数据表中生成如下数据:注意其中为“null”的部分。 · 最后的项目结构如下: 小结: ● 优点:· 实现简单。· 支持多态——对象角色发生变化,或存在多重角色时。· 报表操作实现简单:表中包含了所有信息。● 缺点:· 增加类层次中的耦合。类层次中任何类的属性的增加都会导致表的变更;某个子类属性的修改会影响到整个层次结构,而不仅仅是该子类。· 浪费了一些数据库空间。浪费空间的多少取决于继承层次的深度。层次越深,不同的属性越多,属性的全集就越大,也就越浪费空间。· 可能需要指明具体的角色。 参考:· hibernate – 符合java习惯的关系数据库持久化(第8章)· hibernate 简化继承映射· mapping objects to relational databases: o/r mapping in detail· mapping objects to relational databases 下篇文章会谈谈每个子类一个表的策略。
