java - 在 Hibernate 中遇到 org.hibernate.SessionException : Session is closed! 问题

标签 java hibernate session orm

我对此做了很多研究,但运气不佳,但所有答案都倾向于指向配置文件中的 session 上下文设置。奇怪的是,我第一次访问该页面时就获得了一个 session 连接(因此,一个成功的结果集),但是当我重新加载时,我得到以下异常:org.hibernate.SessionException: session 已关闭!

这是我的与数据库连接字符串无关的配置设置:

<property name="hibernate.show_sql">false</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>        
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_minimal_puts">false</property>

这是我进行的调用的一个示例,它产生了我上面描述的情况。

public T get(int id) {
    session.beginTransaction();
    T type;
    try {
        type = getTypeClass().cast(session.get(getTypeClass(), id));
    } catch (ClassCastException classCastException) {
        throw new ClassCastException(classCastException.getMessage());
    }
    session.getTransaction().commit();
    return type;
}

session 变量引用是指向包含当前 session 的静态字段。所有的 session 连接细节都是教科书引用手册。例如,这是我的 Hibernate session 实用程序:

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactoryUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

最佳答案

当您使用 sessionFactory.getCurrentSession() 获得 Session 时,Session 会在事务提交时自动刷新并关闭(有关详细信息,请参阅 Sessions and transactions)。所以,在这里我怀疑 1. 你一次获得 session (这可以解释为什么第一次调用有效以及为什么后续调用失败)这是错误的,并且 2. 你似乎使用了 session-per-operation 反模式更糟。

在 Web 应用程序中,您应该使用session-per-request 策略,这意味着“单个 Session 和单个数据库事务实现对特定请求事件的处理 em>”。再次引用 Sessions and transactions文档。

如果您想从数据访问代码中删除事务划分,那么您可以使用 interceptor在每个请求开始时启动数据库事务并在请求结束时提交它。看看 Open Session in View实现此模式(使用示例 DAO 展示其优势)。

关于java - 在 Hibernate 中遇到 org.hibernate.SessionException : Session is closed! 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2398446/

相关文章:

具有约束违反异常的 hibernate 批量更新

node.js - NodeJS(Express.js): How to make the Session global

java - 用于分发传感器数据的高效 Java 观察器设计 (~40Hz)

java - 为什么在屏障操作执行后无法立即获取 cyclingBarrier?

java - EclipseLink 在 OneToMany 关系中找不到实体

spring - 使用 @DataJpaTest 时,Hibernate @Formula 在 Spring 启动测试中不起作用

java - 无法使用 Hibernate 空间将几何对象持久保存到 Oracle

php - 使用 MySQL 和 session 登录

.net - 如何在 ASP.NET 中找到无法序列化的对象?

java - 我正在执行插入排序并在我的 while 循环中获取数组越界异常