title: Manage Hibernate Sessions With Spring
body: <p>I have many questions to ask about hibernate sessions, because I'm having continuous issues with them.</p>
  
  <p>I'm using Spring 3.1.1 and Hibernate 4.1.3.</p>
  
  <p>first here is the class diagram that I'm working on.</p>
  
  <p><img src="https://i.stack.imgur.com/ken7s.png" alt="class diagram"></p>
  
  <p>code classes:</p>
  
  <pre><code>public class Equipement {
  
    @ManyToOne(fetch = FetchType.LAZY)
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public getOffice(){
      return office ;
    }
  
  public class Office {    
    @ManyToOne(fetch = FetchType.LAZY)
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public getService(){
      return service ;
    }
  
  public class Service {
    @ManyToOne(fetch = FetchType.LAZY)
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public getDepartement(){
      return departement ;
    }
  </code></pre>
  
  <p>Here is how I load all my equipement.</p>
  
  <pre><code>public class HibernateEquipementDao{
  
    @SuppressWarnings("unchecked")
    public List&lt;Equipement&gt; getAll() {
        return sessionFactory.getCurrentSession().createQuery("from Equipement").list() ;
    }
  }
  </code></pre>
  
  <p>Suppose I load all my equipements in a <code>List&lt;Equipement&gt; allEquipements</code> and want for example to populate my view with only equipements of some service or some departements.</p>
  
  <pre><code> List&lt;Equipement&gt; aListOfEquipements = new ArrayList&lt;Equipement&gt;() ;
   for(Equipement equipement : allEquipements)
     if(equipement.getOffice().getService().getName().equals("name"))
       aListOfEquipements.add(equipement) ;
  </code></pre>
  
  <p>Can I really do this whenever I want ? the session called <strong>Current</strong> is always active ?
  sometimes I get that exception.
  <strong>org.hibernate.LazyInitializationException: could not initialize proxy - no Session</strong></p>
  
  <p>that makes me ask where is the Current session that my EquipementDao use ?</p>
  
  <p>Is there a way to open a session when I want to get the <strong>Departement</strong> of an <strong>Equipement</strong> ?</p>
  
  <p>Or there is another way to proceed ? how manage sessions and how to load all my Equipements and access the other entities with no problems ? </p>