Monday, September 8, 2008

Why won't Hibernate load this collection?

Have you come across this problem? No matter what you do, despite everything looking correct, Hibernate refuses to load a child collection of a parent object when you really really think it should be loading it? Even when debugging, calls to getChildren() return null when you know for sure that there should be something there.

The likely scenario is that the parent/child relationship has not been modelled correctly in the persistence definitions.

Consider the Java Persistence API spec for an idea of how a typical parent-to-children relationship should be defined:

Example 1: One-to-Many association using generics

In Customer class:

@OneToMany(cascade=ALL, mappedBy="customer")
public Set getOrders() { return orders; }

In Order class:

@ManyToOne @JoinColumn(name="CUST_ID", nullable=false)
public Customer getCustomer() { return customer; }



There are two important things to check in your code from the example provided.

  1. "cascade=ALL" is set on the parent. If this is not set, then when you call save on the parent, the children will not be persisted - and usually you do want the children of a parent to be persisted.

  2. "nullable=false" is set on the child (or "optional=false" on the ManyToOne tag). This will ensure that when the child is created, the back-reference to the parent is persisted. If this is not set, then you will be able to create the hierarchy without any problems; but if you forget to explicitly set the parent in your Java code when creating the children you will encounter the problem described before - Hibernate just won't be able to load the children. Setting this element will guarantee that you cannot create the parent/child hierarchy in an invalid state, and will make the cause of any future problems obvious.

It's a good idea to use this snippet as a template when creating a One-to-Many (Parent with Children) relationship, and then you can tinker with the other definition elements as you require them.

0 comments: