Hibernate: Parent/Child relationship in a single-table

前端 未结 3 768
温柔的废话
温柔的废话 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条回答
  •  醉梦人生
    2021-02-15 15:23

    You are expressing two concepts here:

    1. inheritance and you want to map your inheritance hierarchy in a single table.
    2. a parent/child relationship.

    To implement 1., you'll need to use Hibernate's single table per class hierarchy strategy:

    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(
        name="emptype",
        discriminatorType=DiscriminatorType.STRING
    )
    public abstract class Employee { ... }
    
    @Entity
    @DiscriminatorValue("MGR")
    public class Manager extends Employee { ... }
    

    To implement 2., you'll need to add two self-referencing associations on Employee:

    • many employee have zero or one manager (which is also an Employee)
    • one employee has zero or many reportee(s)

    The resulting Employee may looks like this:

    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(
        name="emptype",
        discriminatorType=DiscriminatorType.STRING
    )
    public abstract class Employee { 
    
        ... 
    
        private Employee manager;
        private Set reportees = new HashSet();
    
        @ManyToOne(optional = true)
        public Employee getManager() {
            return manager;
        }
    
        @OneToMany
        public Set getReportees() {
            return reportees;
        }
    
        ...
    }
    

    And this would result in the following tables:

    CREATE TABLE EMPLOYEE_EMPLOYEE (
            EMPLOYEE_ID BIGINT NOT NULL,
            REPORTEES_ID BIGINT NOT NULL
        );
    
    CREATE TABLE EMPLOYEE (
            EMPTYPE VARCHAR(31) NOT NULL,
            ID BIGINT NOT NULL,
            NAME VARCHAR(255),
            MANAGER_ID BIGINT
        );
    
    ALTER TABLE EMPLOYEE ADD CONSTRAINT SQL100311183749050 PRIMARY KEY (ID);
    
    ALTER TABLE EMPLOYEE_EMPLOYEE ADD CONSTRAINT SQL100311183356150 PRIMARY KEY (EMPLOYEE_ID, REPORTEES_ID);
    
    ALTER TABLE EMPLOYEE ADD CONSTRAINT FK4AFD4ACE7887BF92 FOREIGN KEY (MANAGER_ID)
        REFERENCES EMPLOYEE (ID);
    
    ALTER TABLE EMPLOYEE_EMPLOYEE ADD CONSTRAINT FKDFD1791F25AA2BE0 FOREIGN KEY (REPORTEES_ID)
        REFERENCES EMPLOYEE (ID);
    
    ALTER TABLE EMPLOYEE_EMPLOYEE ADD CONSTRAINT FKDFD1791F1A4AFCF1 FOREIGN KEY (EMPLOYEE_ID)
        REFERENCES EMPLOYEE (ID);
    

提交回复
热议问题