您在这里表达两个概念:
- 继承,并且您想要在单个表中映射继承层次结构。
- 父母/子女关系。
要实现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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)