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.
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)