Tuesday, September 14, 2010

Hibernate: Parent and Children

Mapping Model Class:

A single class is used to represent both the parent and children -> CommercialPropertyType.
(The super class PropertyType just provides additional attributes and is not important.)

@Entity
@Table(name = "commercial_property_type")
public class CommercialPropertyType extends PropertyType {

private CommercialPropertyType parent;
private List children;

...

@ManyToOne
@JoinColumn(name = "parent_id")
public CommercialPropertyType getParent() {
return parent;
}

public void setParent(CommercialPropertyType parent) {
this.parent = parent;
}

@OneToMany(cascade = { CascadeType.ALL })
@JoinColumns({ @JoinColumn(name = "parent_id") })
public List getChildren() {
return children;
}

public void setChildren(List children) {
this.children = children;
}
}

Retrieving Data:

Example DAO method to retrieve the top-level parent data with their children data.

@Repository
public class HibernatePropertyTypeDaoImpl extends BaseHibernateDao implements PropertyTypeDao {

@Override
@SuppressWarnings("unchecked")
public List getCommercialPropertyTypes() {
return (List) getPropertyTypesWithChildren(CommercialPropertyType.class);
}

@SuppressWarnings("unchecked")
private List getPropertyTypesWithChildren(Class clazz) {
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(clazz);
//Only get parents
criteria.add(Restrictions.isNull("parent"));
//Get the parent's children if there are any
criteria.createAlias("children", "children", CriteriaSpecification.LEFT_JOIN);
criteria.addOrder(Order.asc("id"));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
}

No comments:

Post a Comment