This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

Question about JPA and lazy loading

 
Eric Miles
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic