File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes EJB and other Java EE Technologies and the fly likes Question about JPA and lazy loading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "Question about JPA and lazy loading" Watch "Question about JPA and lazy loading" New topic

Question about JPA and lazy loading

Eric Miles

Joined: May 20, 2008
Posts: 3
I'm trying to study for the SCBCD exam and am working through some examples to try and get up to speed on JPA. I have some behavior that doesn't make sense to me and I'm hoping you guys can shed some light on it. I'm working through a lazy loading, one-to-many example. I have 2 classes, Fly and FlyBox. FlyBox has a one-to-many unidirectional relationship to Fly that is lazy loaded. Here are relevant snippets of each's code:

I have a stateless session bean that is retrieving a FlyBox and using a left fetch join to also retrieve the associated Fly records for a given FlyBox id. Here is the following Stateless session bean code:

My problem is, is that the number of results returned for a single FlyBox query are proportional to the number of Fly records that particular fly box has (and thus breaks this code). For instance, if I have a FlyBox that has 4 Fly records associated with it, the query will return that same FlyBox record 4 times. If I have a FlyBox with 2 Fly records, the above query attempts to return that FlyBox 2 times.

FYI, if I change the fetch type to eager and remove the fetch join portion of the query, everything is returned appropriately.

What am I missing?

Thanks in advance.
Eric Miles

Joined: May 20, 2008
Posts: 3
LOL, look around enough and you'll find an answer. The following query solves my issue:

However, I'm still not sure why my query functioned the way it did before I added DISTINCT OBJECT. Any info is appreciated.
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968

How do you know it's returning the same Flybox each time?

Could it be putting proxies in place of the records, and you're just looking at the proxies, which by nature, could all be the same? That would make sense for lazy loading.

-Cameron McKenzie
Eric Miles

Joined: May 20, 2008
Posts: 3
I am inspecting the objects in the debugger and they all have the same primary key but are all unique instances (memory addresses). I only have one FlyBox in the database so I know there aren't more than 1.
I agree. Here's the link:
subject: Question about JPA and lazy loading
It's not a secret anymore!