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]?


// creating the session from the sessionfactory
Session session = HibernateConfig.getSessionFactory().openSession();
// fetching
Author authorFetch = (Author)session.get(Author.class, 2);
// closing the session factory session


Full Executable program can be found here


8,186 total views, 6 views today

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.