You might know there are two ways to create or get session in hibernate. We have below two methods in SessionFactory class to create a session.
Tutorial Content:
- Introduction to hibernate framework
- Hibernate hello world example in eclipse
- Difference between openSession and getCurrentSession
- Hibernate one to one mapping example
- Hibernate one to many mapping example
- Hibernate many to many mapping example
- Hibernate inheritance:Table per class hierarchy
- Hibernate inheritance:table per subclass
- Hibernate inheritance:Table per concrete class
- Difference between openSession and getCurrentSession
- Difference between get and load
- Spring MVC Hibernate MySQL CRUD example
- Spring Rest hibernate example
- openSession
- getCurrentSession
openSession
getCurrentSession
1 2 3 4 5 6 7 8 |
<session-factory> <!-- Put other elements here --> <property name="hibernate.current_session_context_class"> thread </property> </session-factory> |
1 2 3 4 5 |
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured! at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) at com.arpit.java2blog.hibernate.HibernateSessionExample.main(HibernateSessionExample.java:14) |
openSession vs getCurrentSession :
Parameter
|
openSession
|
getCurrentSession
|
---|---|---|
Session object
|
It always create new Session object
|
It creates a new Session if not exists , else use same session which is in current hibernate context
|
Flush and close
|
You need to explicitly flush and close session objects
|
You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally
|
Performance
|
In single threaded environment , It is slower than getCurrentSession
|
In single threaded environment , It is faster than getOpenSession
|
Configuration
|
You do not need to configure any property to call this method |
You need to configure additional property “hibernate.current_session_context_class” to call getCurrentSession method, otherwise it will throw exceptions.
|