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

Would this work instead of Hibernate.initialize()?

 
Hussein Baghdadi
clojure forum advocate
Bartender
Posts: 3479
Clojure Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic