📜  org.hibernate.HibernateException:没有配置 CurrentSessionContext! hibernate spring - Html (1)

📅  最后修改于: 2023-12-03 14:44:57.815000             🧑  作者: Mango

org.hibernate.HibernateException: No CurrentSessionContext configured! in Hibernate Spring

If you are using Hibernate Spring and getting the above exception, it means that you have not configured the current session context properly.

What is CurrentSessionContext in Hibernate Spring?

Hibernate Spring uses the concept of a CurrentSessionContext to manage sessions. Essentially, this means that Hibernate Spring creates a Hibernate session for each thread, using a SessionFactory.

Whenever a session is needed, the session context looks up the current thread's session and returns it. If this context is not configured properly, you will get the "No CurrentSessionContext configured!" exception.

How to fix this exception?

The solution to this issue is to correctly configure the current session context in Hibernate Spring. There are several ways to configure the context, but the two most common ones are:

Method 1: Using Spring's OpenSessionInView Filter

The OpenSessionInView filter is a popular solution for managing sessions in Hibernate Spring. Here's how to configure it:

  • Add the following lines to your web.xml:
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
  • Add the following lines to your Hibernate Spring configuration file:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
...
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
Method 2: Using the Spring's CurrentSessionContext

Here's how to configure the Spring's CurrentSessionContext:

  • Add the following lines to your Hibernate Spring configuration file:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
...
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
</props>
</property>
</bean>
Conclusion

In conclusion, the "org.hibernate.HibernateException: No CurrentSessionContext configured!" exception is a common error in Hibernate Spring. The solution is to properly configure the current session context in Hibernate Spring. The two most common methods are using the OpenSessionInView filter or the Spring's CurrentSessionContext.