借助於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>