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
You are expressing two concepts here:
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
:
Employee
)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);