2

Normally, we use Spring + Atomikos to manage the JTA sessions and set hibernate.auto_close_session to true. Now, if we manually open a stateless session (for some async job) as:

StatelessSession sl = sessionFactory.openStatelessSession();

How do we close the StatelessSession? If we call

sl.close()

then the "currentSession" will rollback. If we annotate

@Transactional(propagation = Propagation.NOT_SUPPORTED)

on the method that use the StatelessSession, the commit hangs, the Atomikos log shows that it keep spawning new transactions and never stops.

Full code:

         public Vendor findByCode(String code) {

            StatelessSession slsession = null;
            Transaction tx = null;
            try {
                    slsession = getStatelessSession();
                    tx = slsession.beginTransaction();
                    return (Vendor) slsession.createQuery("from Vendor"
                                    + " where code = :code")
                                    .setParameter("code", code)
                                    .uniqueResult();
            } catch (HibernateException e) {
                    e.printStackTrace();
                    return null;
            } finally {
                    if (slsession != null && tx != null) {
                            tx.commit();
                            slsession.close();
                    }
            }
    }

There is already a Spring managed session, and this method was called.

Could you suggest what is wrong?

4

1 回答 1

0

非常古老的未回答问题,但这里可能是一个答案:您必须回滚您的事务,但您无需关闭会话。除非你真的想。

有一些工具可以防止你在代码中使用它,但它更像是这样的:

        tx.commit();
    } catch (HibernateException e) {
        tx.rollback();
        logger.error(e);
    } 
于 2015-12-13T23:43:37.440 回答