How to work with background threads in a Hibernate / Spring application

I ask how I can work with background threads performing database related tasks in my Hibernate / Spring web application.

I am currently using the following interceptor, so I can annotate the methods of starting a thread using @OpenSession, and the session should be open. This should also work for RMI requests, for example, or any other method that is called without opening a session. However, I'm not sure if the code is correct, I am faced with the problem that sometimes sessions are simply not closed and remain open forever.

@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;
    }
+3
source share
2 answers

, ( - ). @Transactional, EntityManager , , .

+1

JDBC . .

+1

All Articles