java - 为后台线程从 Hibernate 获取新 session

标签 java hibernate web-applications websphere

我正在开发一个网络应用程序。通常在请求开始时(通过架构代码),会打开一个 Hibernate session 来处理 DB 事务。在请求结束时, session 关闭。这对我们所有的交易都非常有效,除了在一个特定的实例中,我想从一个请求中触发一个线程。该线程将调用数据库事务。

在线程中,我调用“sessionFactory.openSession()”,并在这个 session 中执行我的交易。问题在于,当请求完成时,线程本身可能不一定完成。因此,当请求完成并且线程尝试执行另一个数据库事务时,我得到一个 Hibernate Session is Closed!错误。

无论如何,我是否可以从我的线程中打开一个“干净的” session ,与请求开始时打开的 session 无关?

最佳答案

您可以创建一个线程服务,它扩展了 HibernateAccessor,作为一个独立的 Spring 服务,在 spring.xml 中定义,并向它发送您想要的代码/数据过程。像这样:

    Session session = SessionFactoryUtils.getSession(
            getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
    SessionHolder sessionHolder = null;
    try {
        applyFlushMode(session, false);
        sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);
        Transaction t = getSessionFactory().getCurrentSession().beginTransaction();
        try {

            //execute your code here

            t.commit();
        } catch (Exception e) {
            t.rollback();
            log.error("Error", e);
        }
        try {
            flushIfNecessary(sessionHolder.getSession(), false);
        }
        catch (HibernateException ex) {
            throw convertHibernateAccessException(ex);
        }
    } finally {
        SessionFactoryUtils.closeSession(sessionHolder.getSession());
        TransactionSynchronizationManager.unbindResource(getSessionFactory());
    }

关于java - 为后台线程从 Hibernate 获取新 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2337586/

相关文章:

java - 如何修复 [1573451709.039][警告] : Timed out connecting to Chrome, 重试...同时使用 chrome 版本 78 和 chrome 驱动程序版本 78.0.3904.70

java - JPAUpdateClause - 设置值时是否可以连接字符串值?

python - “unicode”对象不可调用

javascript - 如何使用 request.query 获取变量

java - SpringBoot @interface 总结不同注解

java - 动态更改 JTable 中的列数

hibernate - Sybase DBMS 使用哪个连接 JAR?

java - hibernate 不将条目保存到 postgresql 数据库

regex - hibernate 正则表达式

jquery - 保护基于 AJAX 的 Web 应用程序