本篇继续介绍hibernate中的inheritedmapping。 不同与上一篇,这次我们选择选用不同的table来存储相应的父类与子类。 考虑这样一个继承关系mammal与cat,dog。对应的类如下 public class Mammal { private int id; private String name; } public class Cat extends Mammal { private String kind; private int scratchLevel; } public class Dog extends Mammal { private String variety; private int biteLevel; } 由于我们采用不同的table来存储相应的类数据,所以在设计上要选择较比巧妙的方法,即在cat与dog对应的table中采用主键映射的方法。我们将mammal对应的table中的id作为cat与dog的外键,并且在cat与dog对应的table中只存储以下的字段信息: create table cat( cat_id int primary key not null, kind varchar(10) not null, scratchlevel int not null ); create table dog( dog_id int primary key not null, variety varchar(15) not null, bitelevel int not null ); 发现了没?cat与dog从mammal中继承的name域在table中没有相应的字段来存储。由于采用了外键的映射,我们将id与name存入mammal的table中,这样可以节省存储空间,并且很容易进行查找。 那么,外键对应的hibernate描述符如何写呢?我们选用joined-subclass来实现。cat相应的描述如下 <joined-subclass name= "inheritedmapping2.Cat" table= "CAT" > <key column= "CAT_ID" /> <property name= "kind" type= "string" column= "KIND" /> <property name= "scratchLevel" type= "int" column= "SCRATCHLEVEL" /> </joined-subclass> 该片断在Mammal.hbm.xml中。其实除了joined-subclass这个描述字符串以外,其他的都同一般的描述符的一样。通过key,我们将cat table的id与mammal table的id相联系,这样就实现了cat的两个table分开存储。dog中的映射片断与cat相似,改改table与property的值就好了。 查询时,同上一篇一样 List cats = session.find( "from Cat" ); 将选出数据库中全部的cat对象, "from Mammal"将选出所有的对象。 到此,hibernate的inheritedmapping介绍完毕了。 
|