This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara 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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA 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: 3479

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: 17250
    
    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()?