Saturday, May 16, 2009

Hibernate Mapping with parent child relation mapping into same tables

Consider cases when you have parent child relations in the same tables, this becomes very difficult to handle.

In most cases we seperate out mapping of maintaining this parent child relation into another table.

Lets consider an example

we have category which can have subcategories and both these persist on the same table.

Example : Electronics can have subcategory camera, and further camera can have its subcategories.

@Table(name = "t_product_category")
public class ProductCategory {

@Column(name = "f_category_id")
private int categoryId;

@Column(name = "f_category_name")
private String categoryName;

/* The following onetomany relations says that one ProductCategory can have many childrens of teh same type(ProductCategory) identified by
a collection(Set) children.
The initialisation is set to EAGER meaning when you fetch the parent product category all its childeren are automatically
loaded */

@OneToMany(mappedBy = "parent" ,fetch =FetchType.EAGER)
private Set<ProductCategory> children;

/* The following many to one relation means that many(children) of ProductCategory can have a parent of the same kind identified by
parent */

private ProductCategory parent;

public Set<ProductCategory> getChildren() {
return children;

public void setChildren(Set<ProductCategory> children) {
this.children = children;

public ProductCategory getParent() {
return parent;

public void setParent(ProductCategory parent) {
this.parent = parent;

Just by mentioning the two mapping and the corresponding getters & setters our relationship is ready.

Database table looks like this

CREATE TABLE `t_product_category` (
`F_CATEGORY_ID` int(11) NOT NULL auto_increment,
`F_CATEGORY_NAME` varchar(150) NOT NULL,
`F_PARENT` int(11) default NULL,

No comments:

Free Domain Names @!