poornerd

my thoughts on programming and other nerdy stuff

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

| 0 comments

I began hav­ing spo­radic prob­lems in my Play Frame­work 2.0.4 appli­ca­tion where the attrib­utes of ref­er­enced objects were null.

Exam­ple:
When get­ting a Con­tact object with ebean:
Contact contact = Contact.find.byId(id)

contact.user.username
will be null.

How­ever, this will return the cor­rect value:
contact.user.getUsername()

So I started google­ing the prob­lem and found this:

Enhance­ment of direct Ebean field access (enabling lazy load­ing) is only applied to Java classes, not to Scala. Thus, direct field access from Scala source files (includ­ing stan­dard Play 2 tem­plates) does not invoke lazy load­ing, often result­ing in empty (unpop­u­lated) entity fields. To ensure the fields get pop­u­lated, either (angel) man­u­ally cre­ate getter/setters and call them instead, or (beer) ensure the entity is fully pop­u­lated before access­ing the fields.

https://​github​.com/​p​l​a​y​f​r​a​m​e​w​o​r​k​/​P​l​a​y​2​0​/​w​i​k​i​/​J​a​v​a​E​b​ean

This described the prob­lem but offered a poor solution…

Then I found this thread with the answer: http://​stack​over​flow​.com/​q​u​e​s​t​i​o​n​s​/​1​2​9​7​7​5​1​3​/​e​w​o​n​e​t​o​o​n​e​-​r​e​l​a​t​i​o​n​s​h​i​p​-​w​i​t​h​-​p​l​a​y​-​f​r​a​m​e​w​o​r​k​-​t​h​a​t​-​d​o​e​s​-​n​o​t​-​u​s​e​-​j​oin

When load­ing the con­tact, you have to force the load­ing of the user as well!

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

If you have read this far, you may as well fol­low me on Twit­ter:

Author: poornerd

Tech­nol­o­gist, Entre­pre­neur, Vision­ary, Pro­gram­mer :: Grad­u­ated from USC (Uni­ver­sity of South­ern Cal­i­for­nia) with a degree in Com­puter Sci­ence. After 10+ years of free­lance con­sult­ing and pro­gram­ming, he co-founded Site­Force AG eBusi­ness Solu­tions in 1999 in Munich (München), Ger­many.

Leave a Reply

Required fields are marked *.