title: hibernate fetch lazy: Initialize() or HQL
body: <p>Today I learned one tutorial where author explained hibernate association one-to-many / many-to-one.
  I don't want to write all his code here. So, I try to focus on main...</p>
  
  <p>We have two entities: "<strong>Team</strong>" and "<strong>Player</strong>"</p>
  
  <p>In code we have:</p>
  
  <pre><code>@ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="team_id")
  private Team team;
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@OneToMany(mappedBy="team", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private Set&lt;Player&gt; players;
  </code></pre>
  
  <p>The main thing which I interested is type of fetch. So, we inserted one <em>team</em> and some <em>players</em> which are belongs to this <em>team</em>. 
  My DAO class marked with </p>
  
  <pre><code>@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
  </code></pre>
  
  <p>And now I want to load <em>team</em> entity from database with filled collection of <em>players</em>.</p>
  
  <pre><code>Team team = new Team();
  sessionFactory.getCurrentSession().get(team, id);
  
  //and after somewhere in code
  team.getPlayers();
  </code></pre>
  
  <p>At result I will get <code>LazyInitializationException</code>. It's obviously...</p>
  
  <p>We can resolve this problem:</p>
  
  <pre><code>Hibernate.initialize(team.getPlayers());
  </code></pre>
  
  <p>Or we can can load collection of players using HQL. I mean:</p>
  
  <pre><code>Query query = currentSession().createQuery("from Player p where p.team.id =:id");
  query.setParameter("id",key);
  
  team.setPlayers(new HashSet(query.list()));
  </code></pre>
  
  <p>Is it right solutions? And which of them I should use in real development?</p>
  
  <p>And one more question. After I initialized collection of players (no matter which of solutions I used) I can get one of them. Ok, And in "player" entity field Team will initialize. Why? And this <em>team</em> will be with filled player's collection... we have circular dependencies... This is normal?  </p>