Tuesday, December 9, 2008

Convenience methods in Parent / Child relationships in Hibernate

One of the most used associations in ORM is a parent/children relationship. Each parent has a set of children and a child has only one parent. So this is a snippet of a convenience method to manage children from a great book I'm currently reading Java Persistence with Hibernate.

public void addChildCategory(Category childCategory){
   
if(childCategory == null)
       
throw new IllegalArgumentException("Null child category!");
   
if(childCategory.getParentCategory() != null)
       
childCategory.getParentCategory().getChildCategories().remove(childCategory);
   
childCategory.setParentCategory(this);
   
childCategories.add(childCategory);
}

Similarly you can create a removeChildCategory() convenience method.

You probably want to make this methods public and getter/setter methods of the children field private. This will enforce cardinality of the association.

TIP:
Hibernate does not require your entity class to have getter and setter methods. Hibernate will access your entity class properties using Java's Reflection API. So even though your properties are private Hibernate will be able to access them.

In case you have a bidirectional association and your entity class has getter methods than the getter returns a modifiable reference to your children set. This may lead to potential cardinality problem. So, I suggest to wrap your collections in getter method with Collections.unmodifiableCollection(children) and Collections.unmodifiableSet(children).

No comments: