Hibernate: Parent/Child relationship in a single-table

前端 未结 3 786
温柔的废话
温柔的废话 2021-02-15 15:08

I hardly see any pointer on the following problem related to Hibernate. This pertains to implementing inheritance using a single database table with a parent-child relationship

3条回答
  •  猫巷女王i
    2021-02-15 15:27

    I am not sure about you really want, but i think you want a Table per class hierarchy

    In that case, each Entity is sorted by a DISCRIMINATOR_COLUMN as follows

    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(
        name="EMPLOYEE_TYPE", 
        discriminatorType = DiscriminatorType.STRING
    )
    @DiscriminatorValue("EMPLOYEE")
    public class Employee {
    
        @Id @GeneratedValue
        @Column(name="EMPLOYEE_ID") 
        private Integer id = null;
    
    }
    

    And its Children is mapped according to

    @Entity
    @DiscriminatorValue("MANAGER")
    public class Manager extends Employee {
    
        // Manager properties goes here        
         ...
    }
    

    In order to test, let's do the following

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    
    /*
    insert 
    into
        Employee
        (EMPLOYEE_TYPE) 
    values
        ('EMPLOYEE')
    */
    session.save(new Employee());
    
    /*
    insert 
    into
        Employee
        (EMPLOYEE_TYPE) 
    values
        ('MANAGER')
    */
    session.save(new Manager());
    
    session.clear();
    session.close();
    

    But, instead of inheritance (which you can see a lot of NULL column due to more than one Entity share the same table - when using InheritanceType.SINGLE_TABLE strategy), your model would be better as follows

    @Entity
    public class Employee { 
    
        private Employee manager;
        private List reporteeList = new ArrayList();
    
        /**
        * optional=true
        * because of an Employee could not have a Manager
        * CEO, for instance, do not have a Manager
        */  
        @ManyToOne(optional=true)
        public Employee getManager() {
            return manager;
        }
    
        @OneToMany
        public List getReporteeList() {
            return reporteeList;
        }
    
    }
    

    Feel free to choice the best approach that fulfill your needs.

    regards,

提交回复
热议问题