zoukankan      html  css  js  c++  java
  • Hibernate 系列教程11-继承-Single Table策略

    Single Table策略
    通过 discriminator鉴别器来区分是父类还是子类
    Employee

    public class Employee {
      private Long id;
      private String name;

    HourlyEmployee

    public class HourlyEmployee extends Employee {
      private Double rate;

    SalariedEmployee

    public class SalariedEmployee extends Employee {
      private Double salary;

    Employee.hbm.xml

    <class name="Employee" table="t_employee" discriminator-value="1">
            <id name="id">
                <generator class="native" />
            </id>
            <!-- 在id之后配置discriminator的数据库类型的字段名称 ,以及类型(默认是string) -->
            <discriminator column="types" type="int" />
            <property name="name" />
            <!-- 在配置子类 -->
            <subclass name="HourlyEmployee" discriminator-value="2">
                <property name="rate"/>
            </subclass>
            <subclass name="SalariedEmployee" discriminator-value="3">
                <property name="salary" />
            </subclass>
        </class>

    MainTest

    public class MainTest {
      Session session = null;
      @Before
      public void save() {
        session = HibernateUtils.INSTANCE.getSession();
        session.beginTransaction();
    
        Employee employee = new Employee("jege");
    
        HourlyEmployee hourlyEmployee = new HourlyEmployee();
        hourlyEmployee.setName("hourly");
        hourlyEmployee.setRate(200D);
    
        SalariedEmployee salariedEmployee = new SalariedEmployee();
        salariedEmployee.setName("salaried");
        salariedEmployee.setSalary(300D);
    
        session.save(employee);
        session.save(hourlyEmployee);
        session.save(salariedEmployee);
      }
    
      @Test
      public void get() {
        Employee employee = (Employee) session.get(Employee.class, 1L);
        System.out.println(employee.getName());
    
        HourlyEmployee hourlyEmployee = (HourlyEmployee) session.get(HourlyEmployee.class, 2L);
        System.out.println(hourlyEmployee.getName());
        System.out.println(hourlyEmployee.getRate());
    
        SalariedEmployee salariedEmployee = (SalariedEmployee) session.get(SalariedEmployee.class, 3L);
        System.out.println(salariedEmployee.getName());
        System.out.println(salariedEmployee.getSalary());
      }
    
      @After
      public void colse() {
        session.getTransaction().commit();
        session.close();
      }
    }
    

    源码地址

    https://github.com/je-ge/hibernate

    如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!
    微信打赏
    支付宝打赏

  • 相关阅读:
    产品逻辑中的—B端技术常识:同步异步接口模式
    高德地图0907
    高德地图出异常
    svn提交报错
    高德地图demo
    JS中一些特殊的方法
    video标签的学习
    document.getElementById('file').files[0]的jquery写法
    layer请求设置遮罩
    easypoi入门<1
  • 原文地址:https://www.cnblogs.com/je-ge/p/6105498.html
Copyright © 2011-2022 走看看