Play Framework 2.0, Ebean Lazy Loading and Object References that are null

Posted by Brian Porter on January 04, 2013

I began having sporadic problems in my Play Framework 2.0.4 application where the attributes of referenced objects were null.

Example:

When getting a Contact object with ebean:

Contact contact = Contact.find.byId(id)

contact.user.username

will be null.

However, this will return the correct value:

contact.user.getUsername()

So I started googleing the problem and found this:

Enhancement of direct Ebean field access (enabling lazy loading) is only applied to Java classes, not to Scala. Thus, direct field access from Scala source files (including standard Play 2 templates) does not invoke lazy loading, often resulting in empty (unpopulated) entity fields. To ensure the fields get populated, either (angel) manually create getter/setters and call them instead, or (beer) ensure the entity is fully populated before accessing the fields.

https://github.com/playframework/Play20/wiki/JavaEbean</p>

</a>

</blockquote>

This described the problem but offered a poor solution…

Then I found this thread with the answer: <a href=" onclick="javascript:pageTracker._trackPageview('/outbound/article/github.com');"http://stackoverflow.com/questions/12977513/ewonetoone-relationship-with-play-framework-that-does-not-use-join" target="_blank">http://stackoverflow.com/questions/12977513/ewonetoone-relationship-with-play-framework-that-does-not-use-join</a>

When loading the contact, you have to force the loading of the user as well!

Contact contact =<br /> Ebean.find(Contact.class)<br /> .fetch("user")<br /> .where().eq("id", id)<br /> .findUnique();

If you made it this far, you may as well follow me on LinkedIn: Follow Brian Porter