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.
- 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 session.beginTransaction(); Author authorFetch = (Author)session.get(Author.class, 2); System.out.println(authorFetch.getAuthorName()); System.out.println(authorFetch.getSiteName()); session.getTransaction().commit(); // closing the session factory session session.close(); HibernateConfig.getSessionFactory().close();
Full Executable program can be found here
6,516 total views, 6 views today