This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Object Relational Mapping and the fly likes Would this work instead of Hibernate.initialize()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Would this work instead of Hibernate.initialize()?" Watch "Would this work instead of Hibernate.initialize()?" New topic
Author

Would this work instead of Hibernate.initialize()?

Hussein Baghdadi
clojure forum advocate
Bartender

Joined: Nov 08, 2003
Posts: 3476

Hi.
The relationship between Team and Player entities is one-to-many.
Inside a transaction, to fully initialize the player side we could use:
Hibernate.initialize(team.getPlayers());
Well, why not just use:
team.getPlayers();
?
Thanks.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

well the getPlayers, in lazy loading case will just return a Collection with proxy objects. no data has been loaded yet. so just calling getPlayers will not load the data like initialize will. Now if you start looping through the Collection each Player you get out will then be loaded with a single query. This is where the N+1 problem occurs. So if I have 11 players, then Hibernate will run 12 total queries to the database, 1 for the team and 11 for the players. With initialize, you will only get 2 queries. 1 for the team and 1 to initialize the Collection.

This initialize is the same results you would get if you set the fetching strategy to "subselect". Basically the second query run has a sub query in the Where clause to get the players.

For example that second query could look like this

Select players.* from Player players WHERE players.team_id = (Select team.id from Team team)

does that help?

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Would this work instead of Hibernate.initialize()?
 
Similar Threads
With JPA how can I force loading of nested lazy collections?
WA #1.....word association
i not wnat to lazy initialization
transient fields and entityManager.refresh
Hibernate 3 eager fetching