title: When to close database connection in hibernate?
body: <p>Firstly it may sound like a duplicate question but i didn't get solution i was expecting so I am posting this new question?I have started learning hibernate a couple of days ago.I am stuck on this 1 thing:</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public static void open_connection()
  
  sessionfactory=new Configuration().configure().buildSessionFactory();
  Listsession = sessionfactory.openSession();
  }
  
  public  List select(String qry)
  { 
      open_connection();  
      Listsession.beginTransaction();
      query =Listsession.createQuery(qry);
      list=query.list();
      Listsession.getTransaction().commit();
      Listsession.close();
      sessionfactory.close();
      }
  </code></pre>
  
  <p><strong>Q1.</strong> I have closed the sessionfactory when a query has run.Is it a good approach?I want to close database connection when we don't need it as we do in JDBC(My teacher taught me that).</p>
  
  <p><strong>Q2.</strong> Should I close connection when user is getting logout from my site?</p>
  
  <p><strong>Q3.</strong> Will sessionfactory.close(); also destroy my session variable(session.setattribute("user",ur);).</p>
  
  <p><strong>Q4.</strong> Does   Listsession.getTransaction().commit(); also close the transaction?</p>
  
  <p>I want to know this because many times i run my project on netbeans i am getting null pointer exception but when i run same project online i don't get null pointer exception and i think this happens because openconnection is called everytime i run my project. 
  Sorry for posting so many questions as i couldn't get exact answers i was looking for.</p>