Hibernate继承、多态查询(五)

继承映射、多态查询

  通过hibernate如何实现继承,有三种方式:

   1):每个子类一张表。每个子类对应一个hbm.xml文件,但是父类没有对应的hbm.xml文件。


Public class Parent implements Serilizable{
   Private Long id;//主键
   Private String name;
    ...setter/getter...
}
Public class Child1 implmemts Parent,Serilizable{
   Private String cardNumber;
}
Public class Son implements Parent,Serilizable{
  Private String loves;
}

Child1.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name= “Child1” table = “child_”>
       <!--继承父类的id,这里的继承并不是通过私有属性继承的,私有的属性是无法继承的,而是通过对应的getter/setter方法继承过来的-->
      <id name= “id” column = “id” type = “long”>
         <generator class = “increment”/>
      </id>
     <!--配置继承了父类的属性-->
     <property name = “name” column = “name” type = “string”/>
     <!--配置自己的属性-->
     <property name= “cardNumber” column = “cardNumber” type = “string”/>
   </class>
</hibernate-mapping>
对于Som.hbm.xml一样的进行配置

多态查询
Public void test(){
    SessionFactory factory = new Configuration().configure();
  Session session = factory.openSession();
  Transaction tx = null;
  Try{
      Tx = session.beginTransaction();
      //注意这里并没有Parent.hbm.xml文件,因此在查询时,需要写全名,多态查询
      Query query = session.createQuery(“from com.test.Parent”);
      List<Parent> list = (List<Parent>)query.list();
      For(Parent p :list){
         If(p instanceOf Child1){
              //这里得到的就是Child1对象
          }else if(p instanceOf Son){
             //这里得到的就是Son对象
          }
      }
      Tx.commit();
  }catch(Exception e){
      If(null != tx)
          tx.rollBack();
  }finally{
      If(null != session)session.close();
  }
}

2):所有的子类都在同一个表中(会造成字段浪费),只针对父类有hbm.xml,其余没有

Parent.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
     <class name= “Parent” table= “parent_”>
         <id name= “id” column = “id” type = “long”>
            <generator class = “increment”/>
        </id>
       <!--配置父类的属性-->
       <property name= “name” column = “name” type = “string”/>
       <!-- 配置继承了该父类的子类的所有字段name为子类的名字,同时要配合元素discriminator指定一个区分值 -->
        <subclass name="Child1" discriminator-value="child1">
           <property name="cardNumber" column="cardNumber" type="string">
            </property>
        </subclass>
        <subclass name="Son" discriminator-value="son">
            <property name="loves" column="loves" type="string">
             </property>
        </subclass>
    </class>
</hibernate-mapping>

3):父类信息放置在一张表中,每个子类都有自己的表,但存放自己独有的东西。

      ...略....



你可能感兴趣的:(Hibernate,继承,orm,多态,应用)