zoukankan      html  css  js  c++  java
  • Hibernate 系列教程14-继承-PerTable策略

    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">
            <id name="id">
                <!-- 不能使用native的主键生成方式 -->
                <generator class="org.hibernate.id.enhanced.TableGenerator" />
            </id>
            <property name="name" />
            <!-- 在配置子类 -->
            <union-subclass name="HourlyEmployee" table="t_HourlyEmployee">
                <property name="rate" />
            </union-subclass>
            <union-subclass name="SalariedEmployee" table="t_SalariedEmployee">
                <property name="salary" />
            </union-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

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

  • 相关阅读:
    【转载】Java的JVM原理
    【转载】Java容器的线程安全
    【转载】Java中的容器讲解
    【转载】Java集合容器全面分析
    【转载】Java多线程
    【转载】Java泛型(一)
    09_dubbo服务发布原理
    07_dubbo_compiler
    06_javassist
    05_dubbo_aop
  • 原文地址:https://www.cnblogs.com/je-ge/p/6105421.html
Copyright © 2011-2022 走看看