美文网首页Hibernate 菜鸟教程
Hibernate 菜鸟教程 12 继承 Join策略

Hibernate 菜鸟教程 12 继承 Join策略

作者: JeGe | 来源:发表于2016-12-18 17:38 被阅读16次

    模型对象

    父类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">
                <generator class="native" />
            </id>
            <property name="name" />
            <!-- 在配置子类 -->
            <joined-subclass name="HourlyEmployee" table="t_HourlyEmployee">
                <key column="id"/>
                <property name="rate" />
            </joined-subclass>
            <joined-subclass name="SalariedEmployee" table="t_SalariedEmployee">
                <key column="id"/>
                <property name="salary" />
            </joined-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

    如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
    **您的支持将鼓励我继续创作!谢谢! **

    微信打赏微信打赏
    支付宝打赏支付宝打赏

    相关文章

      网友评论

        本文标题:Hibernate 菜鸟教程 12 继承 Join策略

        本文链接:https://www.haomeiwen.com/subject/edhzmttx.html