File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

Would this work instead of Hibernate.initialize()?

Hussein Baghdadi
clojure forum advocate

Joined: Nov 08, 2003
Posts: 3479

The relationship between Team and Player entities is one-to-many.
Inside a transaction, to fully initialize the player side we could use:
Well, why not just use:
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

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 from Team team)

does that help?


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
I agree. Here's the link:
subject: Would this work instead of Hibernate.initialize()?
It's not a secret anymore!