JPA 2 Eager Fetching on a Collection

Quick little JPA 2 issue that I faced today that I’m sure many other people have run into especially when starting out. The problem was and error message such as the one shown below when attempting to display the contents of a Set of other entities in a JSF page

The class 'org.eclipse.persistence.indirection.IndirectSet' does not have the property Foo

The page was using a data table to display the set and the error message is telling me that the “#{}” call that I had made failed. Fortunately I quickly realized what the problem was. Earlier on I had changed a relationship from OneToOne to OneToMany and a OneToMany relationship is lazy loaded by default under JPA. The solution was to change the annotation on the relationship so that it fetched eagerly like this:

@OneToMany( fetch= FetchType.EAGER )

Now, when I come to display this set of objects in JSF page it will be present rather than simply being a place holder “IndirectSet” object. Of course there are draw backs to making a relationship eager like this the most obvious one being the additional memory used and the time taken to query for the other objects.

There are several strategies for avoiding detachment (which I might discuss later) so that items can be lazy loaded as needed but all of them feel like a bit of a kludge to me. In this case, fortunately, the overhead of making this relationship eager was pretty small.