6-Descriminator的应用示例

1-父类HBM

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping >

   <class name="mypack.Employee" table="EMPLOYEES">
      <id name="id" type="long" column="ID">  /*ID*/
      <generator class="increment"/>
      </id>
      <discriminator column="EMPLOYEE_TYPE" type="string"  />  /*不用再专门映射属性啦*/
      <property name="name" type="string" column="NAME" />

      <many-to-one    /*作为一对多关联中多的一方,映射compamy属性 */
        name="company"
        column="COMPANY_ID"
        class="mypack.Company"
      />

      <subclass name="mypack.HourlyEmployee" discriminator-value="HE" >
         <property name="rate" column="RATE" type="double" /> /*子类的属性都在这里映射,没有单独的.hbm.xml*/
      </subclass>

      <subclass name="mypack.SalariedEmployee" discriminator-value="SE" >
         <property name="salary" column="SALARY" type="double" /> /*子类属性映射,没有hbm.xml*/
      </subclass>
    
    </class>
 
</hibernate-mapping> 

2-一对多关联 主控方HBM

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping >

  <class name="mypack.Company" table="COMPANIES" >
    <id name="id" type="long" column="ID">
      <generator class="increment"/>
    </id>

    <property name="name" type="string"  column="NAME" />
    <set
        name="employees"
        inverse="true"
        lazy="true"
    >
        <key column="COMPANY_ID" />
        <one-to-many class="mypack.Employee" />
       </set>
  

</class>
</hibernate-mapping>

2-服务类

package mypack;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import java.util.*;
import java.sql.*;

public class BusinessService{
  public static SessionFactory sessionFactory;
  static{
     try{
      // Create a configuration based on the properties file we've put //因为子类没有hbm文件,要加入子类
       Configuration config = new Configuration();
       config.addClass(Company.class) .addClass(Employee.class);
       // Get the session factory we can use for persistence
      sessionFactory = config.buildSessionFactory();
    }catch(Exception e){e.printStackTrace();}

  }

  public void saveEmployee(Employee employee) throws Exception{
      Session session = sessionFactory.openSession();
      Transaction tx = null;
      List results=new ArrayList();
      try {
       tx = session.beginTransaction();
       session.save(employee);
       tx.commit();
    }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
  }


  public List findAllHourlyEmployees() throws Exception{
      Session session = sessionFactory.openSession();
      Transaction tx = null;

      try {

       tx = session.beginTransaction();
       List results=session.find("from HourlyEmployee");
       tx.commit();
       return results;
    }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
  }

  public List findAllEmployees() throws Exception{
      Session session = sessionFactory.openSession();
      Transaction tx = null;

      try {
       tx = session.beginTransaction();
       List results=session.find("from Employee");
       tx.commit();
       return results;
     }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
  }

  public Company loadCompany(long id) throws Exception{
      Session session = sessionFactory.openSession();
      Transaction tx = null;
      try {
       tx = session.beginTransaction();
       Company company=(Company)session.load(Company.class,new Long(id));
       Hibernate.initialize(company.getEmployees());
      tx.commit();
      return company;
    }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
  }

   public void test() throws Exception{
      List hourlyEmployees=findAllHourlyEmployees();
      printAllEmployees(hourlyEmployees.iterator());

      List employees=findAllEmployees();
      printAllEmployees(employees.iterator());

      Company company=loadCompany(1);
      printAllEmployees(company.getEmployees().iterator());

      Employee employee=new HourlyEmployee("Mary",300,company);
      saveEmployee(employee);

  }

  private void printAllEmployees(Iterator it){
     while(it.hasNext()){
        Employee e=(Employee)it.next();
        if(e instanceof HourlyEmployee){
          System.out.println(((HourlyEmployee)e).getRate());
        }else
          System.out.println(((SalariedEmployee)e).getSalary());
      }
  }
  public static void main(String args[]) throws Exception {
    new BusinessService().test();
    sessionFactory.close();
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值