Hibernate: Parent/Child relationship in a single-table
- by Dee
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 to itself. For example:
CREATE TABLE Employee (
empId BIGINT NOT NULL AUTO_INCREMENT,
empName VARCHAR(100) NOT NULL,
managerId BIGINT,
CONSTRAINT pk_employee PRIMARY KEY (empId)
)
Here, the managerId column may be null, or may point to another row of the Employee table. Business rule requires the Employee to know about all his reportees and for him to know about his/her manager. The business rules also allow rows to have null managerId (the CEO of the organisation doesn't have a manager).
How do we map this relationship in Hibernate, standard many-to-one relationship doesn't work here? Example code would be appreciated.