Difference between session and sessionfactory hibernate?

Difference between session and sessionfactory hibernate?

Basically session will be created from the sessionfactory instances. I have listed down the few differences between the session and sessionfactory in hibernate.


  • It is one instance per datasource/database.
  • It is thread safe.
  • It is a heavy weight object, because it maintains datasources, mappings, hibernate configuration information’s etc.
  • Sessionfactory will create and manage the sessions.
  • If you have 5 datasources/databases, then you must create 5 session factory instances.
  • sessionfactory is an immutable object and it will be created as singleton while the server initializes itself.

What is session factory & How to create a sessionfactory ?


  • It is one instance per client/thread/one transaction.
  • It is not thread safe.
  • It is light weight.
  • sessions will be opened using sessionfactory.openSession() and some database operations will be done finally session will be closed using session.close().


How Session will be created from session factory [sample snippet]?


<div class="line number23 index22 alt2"><code class="java comments">// creating the session from the sessionfactory</code></div>
<div class="line number24 index23 alt1"><code class="java plain">Session session = HibernateConfig.getSessionFactory().openSession();</code></div>
<div class="line number25 index24 alt2"></div>
<div class="line number26 index25 alt1"><code class="java comments">// fetching</code></div>
<div class="line number27 index26 alt2"><code class="java plain">session.beginTransaction();</code></div>
<div class="line number28 index27 alt1"><code class="java plain">Author authorFetch = (Author)session.get(Author.</code><code class="java keyword">class</code><code class="java plain">, </code><code class="java value">2</code><code class="java plain">);</code></div>
<div class="line number29 index28 alt2"><code class="java plain">System.out.println(authorFetch.getAuthorName());</code></div>
<div class="line number30 index29 alt1"><code class="java plain">System.out.println(authorFetch.getSiteName());</code></div>
<div class="line number31 index30 alt2"><code class="java plain">session.getTransaction().commit();</code></div>
<div class="line number32 index31 alt1"></div>
<div class="line number33 index32 alt2"><code class="java comments">// closing the session factory session</code></div>
<div class="line number34 index33 alt1"><code class="java plain">session.close();</code></div>
<div class="line number35 index34 alt2"></div>
<div class="line number36 index35 alt1"><code class="java plain">HibernateConfig.getSessionFactory().close();</code></div>


Full Executable program can be found here


617 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *