title: org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
body: <p>I keep on getting this error "Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed" when I run the following code:</p>
  
  <pre><code>public ArrayList&lt;ProfileDTO&gt; getInitialProfiles(Contracts ct){ 
     SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
     Session session=sessionFactory.openSession();
     Transaction tx=session.beginTransaction(); 
     ArrayList&lt;ProfileDTO&gt; profileDTOs=new ArrayList&lt;ProfileDTO&gt;();
     try{
         Hibernate.initialize(ct);
          SQLQuery query=session.createSQLQuery("select {b.*},{p.*},{t.*} from bidtool.bt_boiler_plates b,bidtool.bt_profile p,bidtool.bt_trade_lane t where b.contract_id=:val AND p.contract_id=:val AND t.contract_id=:val")
                    .addEntity("b",Boiler_Plates.class)
                    .addEntity("p",BidToolProfiles.class)
                    .addEntity("t",BidToolTradeLanes.class);
          query.setParameter("val", ct.getContract_id());
          List list=query.list();  
  
          Iterator iteContract = list.iterator();
          while ( iteContract.hasNext() ) {
              Object[] pair =(Object[]) iteContract.next();
              Boiler_Plates bp=(Boiler_Plates)pair[0];
              BidToolProfiles p=(BidToolProfiles)pair[1];
              ProfileDTO profileDTO=new ProfileDTO();
              profileDTO.setProfileId(p.getProfileId());
              profileDTO.setBt_contracts(p.getBt_contracts());
              profileDTO.setCreated(p.getCreated());
              profileDTO.setProfileContent(p.getProfileContent());
              profileDTO.setEditable(p.getEditable());
              profileDTO.setProfileName(p.getProfileName());
              profileDTOs.add(profileDTO);
          } 
          return profileDTOs;
     }
     catch(Exception ex){
         System.out.println(ex.getMessage());
         return profileDTOs;
     }
     finally{
      session.flush();   
      session.close();
     }
   }
  </code></pre>
  
  <p>It works fine whenever I don't close the session but I cannot do that. I need to close the session. Your help will be appreciated. Thank you.</p>