【IT168 技术文档】在我们实际设计过程中,经常碰到类的继承关系,比如一个电子产品商店,同时销售手机和MP3,所以在设计系统的时候我们把手机和MP3的共性如品牌、名称等抽象为一个类,而把它们的特性比如MP3有内存容量,手机有号码等,我们以不同的子类来体现。如下图:
在实际数据库的时候,最简单的就是每个子类拥有一个独立的表分别对应Mp3player和MobilePhone
由于MobilePhone和Mp3Player都是继承electronic,所以他们都Id,Name,Brand等属性,了我们分别为两个表编写映射文件:
MobilePhone.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="QuickStart2.Data.MobilePhone, QuickStart2.Data" table="t_mobilephone" >
<id name="Id" column="id" type="Int32">
<generator class="identity" />
</id>
<property name="Name" type="String(100)" column="name" />
<property name="Brand" type="String(20)" column="brand" />
<property name="Phonenumber" type="String(13)" column="phonenumber" />
</class>
</hibernate-mapping>
Mp3Player.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="QuickStart2.Data.Mp3Player, QuickStart2.Data" table="t_mp3player" >
<id name="Id" column="id" type="Int32">
<generator class="identity" />
</id>
<property name="Name" type="String(100)" column="name" />
<property name="Brand" type="String(20)" column="brand" />
<property name="Mensize" type="Int32" column="mensize" />
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="QuickStart2.Data.MobilePhone, QuickStart2.Data" table="t_mobilephone" >
<id name="Id" column="id" type="Int32">
<generator class="identity" />
</id>
<property name="Name" type="String(100)" column="name" />
<property name="Brand" type="String(20)" column="brand" />
<property name="Phonenumber" type="String(13)" column="phonenumber" />
</class>
</hibernate-mapping>
Mp3Player.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="QuickStart2.Data.Mp3Player, QuickStart2.Data" table="t_mp3player" >
<id name="Id" column="id" type="Int32">
<generator class="identity" />
</id>
<property name="Name" type="String(100)" column="name" />
<property name="Brand" type="String(20)" column="brand" />
<property name="Mensize" type="Int32" column="mensize" />
</class>
</hibernate-mapping>
可以看到这两个映射和普通的映射文件没有什么不同。我们编写了一个段测试代码:
ISession session=null;
ArrayList list=null;
try{
session=SessionFactory.OpenSession();
list=(ArrayList)session.CreateCriteria(typeof(electronic)).List();
}
catch(Exception e) {
System.Console.WriteLine(e.Message);
System.Console.ReadLine();
}
finally{
session.Close();
}
foreach(electronic el in list) {
System.Console.WriteLine("名称:º"+el.Name);
}
ArrayList list=null;
try{
session=SessionFactory.OpenSession();
list=(ArrayList)session.CreateCriteria(typeof(electronic)).List();
}
catch(Exception e) {
System.Console.WriteLine(e.Message);
System.Console.ReadLine();
}
finally{
session.Close();
}
foreach(electronic el in list) {
System.Console.WriteLine("名称:º"+el.Name);
}
运行结果如下图所示: