休眠:单表中的父子关系

休眠:单表中的父子关系,第1张

休眠:单表中的父/子关系

您在这里表达两个概念:

  1. 继承,并且您想要在单个表中映射继承层次结构。
  2. 父母/子女关系。

要实现1.,您需要使用每个类层次结构策略的Hibernate
单个表:

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

要实现2.,您需要在上添加两个自引用关联

Employee

  • 许多员工有零个或一个经理(也是
    Employee
  • 一名员工的报告人为零或很多

结果

Employee
可能如下所示:

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

这将导致下表:

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);


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5015751.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存