Getting a new session from Hibernate for a background thread

I am working on a web application. Typically, at the beginning of a query (via architecture code), a Hibernate session is opened to work with DB transactions. At the end of the request, the session is closed. This works great for all of our transactions, except that in one specific case I want to start a thread from a request. This thread will trigger database transactions.

From the thread, I call "sessionFactory.openSession ()", and with this session I am executing my transactions. The problem is that when the request ends, the thread itself may not necessarily be completed. Therefore, when the request completes and the thread tries to execute another database transaction, I get a Hibernate session that is closed! error.

In any case, from my stream, can I open a "clean" session, not related to the one that was opened at the beginning of the request?

+5
source share
2 answers

You can create a streaming service that extends HibernateAccessor, like the standalone Spring service defined in spring.xml, and sends it the code / data that you want to process. Something like that:

    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());
    }
+1
source

You can use JPA Entity Manager to start and commit transactions manually. Here is my extended answer

0
source

All Articles