java - 如何处理 Hibernate/Spring 应用程序中的后台线程

标签 java hibernate spring jakarta-ee

我问我应该如何处理在我的 Hibernate/Spring 网络应用程序中执行涉及数据库的任务的后台线程。

目前我正在使用以下拦截器,所以我可以用@OpenSession 注释我的线程运行方法,并且应该打开一个 session 。例如,这也适用于 RMI 请求或在没有打开 session 的情况下调用的任何其他方法。但是,我不确定代码是否正确,我遇到的问题是有时 session 不会关闭并永远保持打开状态。

@Around("@annotation(openSession)")
    public Object processAround(ProceedingJoinPoint pjp, OpenSession openSession) throws Throwable {

        boolean boundResource = false;
        Session session = null;

        // Bind the session to the thread, if not already done
        if(TransactionSynchronizationManager.getResource(sessionFactory) == null) {
            log.debug("Opening Hibernate Session in method "+pjp.getSignature());

            session = SessionFactoryUtils.getSession(sessionFactory, true);
            TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
            boundResource = true;
        }

        // Invoke the annotated method
        Object ret;
        try {
            ret = pjp.proceed();
        }
        catch(Throwable t) {
            // Rethrows the Exception but makes sure the session will be closed
            SessionFactoryUtils.closeSession(session);
            log.debug("Closing Hibernate Session in method (Exception thrown) "+pjp.getSignature());
            throw t;
        }

        // If a resourc was bound by this method call, unbind it.
        if(boundResource) {
            //SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
            session.flush();
            SessionFactoryUtils.closeSession(session);

            log.debug("Closing Hibernate Session in method "+pjp.getSignature());
        }

        return ret;
    }

最佳答案

是的,您建议的解决方案应该可行(我自己也做过类似的事情)。如果您只使用 @Transactional,您将为每个事务获得一个新的 EntityManager,如果您的后台线程有很多事务,这不一定是最佳的。

关于java - 如何处理 Hibernate/Spring 应用程序中的后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6375588/

相关文章:

java - 更新子实体但保存父实体会导致 ObjectOptimisticLockingFailureException

spring - 从 Web 应用程序和 Apache Camel/并使用 MQ,您是否使用 jsessionid 添加 JMS 消息?

java - 使用JLine在一行完成多条命令

java - 如何使用 Scanner 仅接受有效的 int 作为输入

java - Libgdx 变量类型的内存大小

hibernate - Spring Boot JPA不会在查询表中添加模式名称

java - 从 JSF 访问 JPA 元组属性

java - 在 Java 中连接多维数组的最佳方法是什么?

java - 在 OneToMany 和 ManyToMany 映射中获取 StackOverflow

java - Spring 的 UriComponentsBuilder.queryParam 问题