📅  最后修改于: 2023-12-03 14:44:57.815000             🧑  作者: Mango
If you are using Hibernate Spring and getting the above exception, it means that you have not configured the current session context properly.
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.
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:
The OpenSessionInView filter is a popular solution for managing sessions in Hibernate Spring. Here's how to configure it:
<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>
<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>
Here's how to configure the Spring's CurrentSessionContext:
<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>
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.