借助于Hibernate强大的O/R Mapping能力,我们能够通过discriminator轻易地将一颗继续树映射到一个表中,通过discriminator确定具体映射的子类。
在设置@hibernate.discriminator column="type" type="integer"后,启动Hibernate报错:
Could not format discriminator value to SQL string
搜索Hibernate官方文档后发现问题,原来Hibernate默认的discriminator的type是String,当设置discriminator的type为integer后,需要为父类也设置@hibernate.class table="TABLE_NAME" discriminator-value="not null",否则,Hibernate默认的discriminator-value是完整的类名,在转换String到int时造成NumberFormatException。
最后运行XDoclet,生成hbm文件:
<?XML version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.crackj2ee.example.AbstractClass" table="TABLE_NAME" discriminator-value="not null">
<id name="id" column="id" type="Java.lang.Long" unsaved-value="null">
<generator class="increment"/>
</id>
<discriminator column="type" not-null="true" type="integer"/>
<subclass name="com.crackj2ee.example.SubClass1" discriminator-value="1">
<subclass name="com.crackj2ee.example.SubClass2" discriminator-value="2">
</class>
</hibernate-mapping>