How to implement a self join in hibernate

Source : http://viralpatel.net/blogs/hibernate-self-join-annotations-one-to-many-mapping/

We have a create table in the database.

CREATE TABLE employee (
employee_id NUMBER(10) NOT NULL,
firstname VARCHAR2(50) NULL DEFAULT NULL,
lastname VARCHAR(50) NULL DEFAULT NULL,
manager_id NUMBER(10) NULL DEFAULT NULL,
PRIMARY KEY (’employee_id’),
CONSTRAINT ‘FK_MANAGER’ FOREIGN KEY (‘manager_id’) REFERENCES ’employee’ (’employee_id’)
);

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

We will be using annotations to implement this in hibernate:

@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id
@Column(name="EMPLOYEE_ID")
@GeneratedValue
private Long employeeId;

@Column(name="FIRSTNAME")
private String firstname;

@Column(name="LASTNAME")
private String lastname;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="manager_id")
private Employee manager;

@OneToMany(mappedBy="manager")
private Set subordinates = new HashSet();

public Employee() {
}

public Employee(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}

// Getter and Setter methods
}

Note that in Employee entity class, we defined two new attributes: Employee manager and Set 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.

About Vineet Verma

Developer/Blogger/Gamer/Lazy Couch Potato...:P Need PDF Books: Knowledge Base
This entry was posted in Hibernate. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s