org.hibernate.HibernateException:未配置CurrentSessionContext

时间:2020-02-23 14:44:23  来源:igfitidea点击:

Hibernate需要进行大量配置,有时您会得到奇怪的异常,并且没有任何线索表明这是由于缺少某些配置。

org.hibernate.HibernateException: No CurrentSessionContext configured

我正在开发一个简单的休眠Web应用程序,并遇到异常。

org.hibernate.HibernateException: No CurrentSessionContext configured!
	org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)
	com.theitroad.servlet.hibernate.GetEmployeeByID.doGet(GetEmployeeByID.java:31)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

当我查看源代码时,抛出异常的语句是:

Session session = sessionFactory.getCurrentSession();

我的Hibernate配置是这样的:

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>

      <!-- Mapping with model class containing annotations -->
	<mapping class="com.theitroad.servlet.hibernate.model.Employee"
  </session-factory>
</hibernate-configuration>

修复org.hibernate.HibernateException:未配置CurrentSessionContext

在我看来,一切都很好,但异常情况并未明确说明缺少的内容。

经过SessionFactoryImpl之后,我发现我们还需要配置当前会话上下文类以获取当前会话。

这是在方法buildCurrentSessionContext()中完成的,它会寻找属性hibernate.current_session_context_class。

从方法主体可以明显看出,此属性的值应为:

  • jta获取JTASessionContext
  • ManagedSessionContext的" managed"
  • ThreadLocalSessionContext的" thread"

如果我们提供上述类名,则该方法也适用。
因此,当我在休眠配置文件中添加此属性时,程序开始正常运行。

Hibernate CurrentSessionContext类的配置示例

定义current_session_context_class属性的示例方法是:

<property name="hibernate.current_session_context_class">thread</property>

如果您的休眠配置文件具有xml格式,请使用以下配置。

<property name="hibernate.current_session_context_class">
org.hibernate.context.internal.ThreadLocalSessionContext
</property>