Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement Many to Many relationship using Annotation mapping. In this tutorial we will modify the source code from previous Many To Many XML mapping tutorial and add JPA/Annotation support to it.
Self Join: One to Many
In a query, a table that is related to itself by two different fields. For example, an employee table can include the ID of a manager who is also in the same table.
A Self-Join or Self-Reference is basically one which has some sort of Parent/Child sturcture. We will see an example where we implement Self-Join in class of same type. For example Manager / Subordinates relationship.
Let us see how to implement Self Reference One-to-Many relationship in Hibernate using Annotation.
1. Create Database
For this example, we will MySQL database. We are using Manager / Subordinates relationship as a Self-Join One to Many mapping example. Each manager is an employee. Hence we implement a Parent/Child relationship in Employee enitity.
Here in Employee table, we defined a column MANAGER_ID which is mapped to the same table’s primary key. Thus for each employee we will store its manager’s id also. Manager will be yet another employee in this table.
Note that in Employee entity class, we defined two new attributes: Employee manager and Set<Employee> subordinates. Attribute manager is mapped with @ManyToOne annotation and subordinates is mapped with @OneToMany. Also within @OneToMany attribute we defined mappedBy="manager" making manager as the relationship owner and thus which manages the foreign relationship within table.
Also the annotation @JoinColumn is defined on manager making it the relationship owner. @JoinColumn defines the joining column which in our case is manager_id.
4. Hibernate Configuration File
Edit Hibernate configuration file (hibernate.cfg.xml) and add mappings for Employee and Meeting classes. Following is the final hibernate.cfg.xml file:
We created one manager “Chuck Norris” and two employees “Sergey Brin” and “Larry Page”. We set the manager details for each employees and saved the employee. Following are the sql statements generated by Hibernate.