Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help understanding when to use em.find and query manager and their ability to fetch nested objects

 
john lazeraski
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am trying to understand why my @OneToOne (eager load by default) will not load a nested object when I use a query to find it. I could be doing something wrong of course. I have a simple class:




So.. when I do a lookup for an email, and find it, it loads the EmailEntity instance. With a @OneToOne, it should load the User instance. The user, with it's @OneToOne to Address should load that..should it not? Or does the @OneToOne on a query only work one level deep for related objects?

I read that em.find(SomeClass.class, id) will load the entire tree of objects.. is this true? Does the Query object do the same when you use getSingleResult or getResultList?

I am not sure what I am doing wrong, but when I load an email and call getUser() the user object is retrieved. But email.getUser().getAddress() returns null. Should that not be null.. and/or should getAddress().getState() also not be null on both an em.find() and an Query ?

Thanks.
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every relationship that finishes in One (@OneToOne, @ManyToOne) will be eagerly loaded.
The relationships that finishes with Many (@ManyToMany, @OneToMany) by default will be lazy loaded.

The em.find() will follow this rules by default.
 
john lazeraski
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok..that much I was hoping I understood.. so that does mean then that an entity nested 3 levels down (in my exmaple, email->user->address->state) would load?

The one that doesn't seem to work for me is using the query manager. Does query manager ALSO load all eager loaded nested entities all the way down the chain? Or do I have to loop through each item (or grab each item) and do another query and set it on the parent object to get nested entity data?

So here I am looking for an email by its string value in an email table using a named query. When it finds the email, the getUser() should return the user object that the email is tied to (user has one to many emails attached to it). At that point, will the getUser().getAddress().getState() work via the query on email?

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic