How to resolve "Could not obtain transaction-synchronized Session for current thread" exception

149 views Asked by At

I'm working on an old could base that is using Spring Framework / Hibernate 4. There is job started with "org.springframework.scheduling.quartz.JobDetailFactoryBean"

Simplified Example.

public class MyJob {

    public class MyManagerImpl extends QuartzJobBean {

        private CustomerManager customerManager = null;
        private MyDAO myDAO = null;
        private PlatformTransactionManager transactionManager;

        void executeInternal(final JobExecutionContext ctx) throws JobExecutionException {
            new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
                int count = getRecordsToProcess(..);
                for (int i = 0;      i<count;i++)  {
                    processRecord(i);
                }
                // transactionManager.commit(status) // throws exception  
                return null;
            });
        }
    }
}

This code is working today, but I need to change it to commit after each record is processed. This seems like it should be a simple line add "transactionManager.commit(status) but when myDAO is called it throws below.

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014) at com.cs.dao.impl.BaseDAOHibernate.getSession(BaseDAOHibernate.java:24) at com.cs.dao.impl.MyJdbcDAO.nextId(BadgeJdbcDAO.java:151) at com.monitor.service.impl.MyManagerImpl.processRecord(

Code from MyJdbcDAO:


public Long nextId() {
    String queryString = "SELECT BADGE_ID_SN.NEXTVAL FROM DUAL";
    Query queryObject = this.getSession().createSQLQuery(queryString);
    return ((BigDecimal)queryObject.list().get(0)).longValue();
}

protected Session getSession() {
    return getSessionFactory().getCurrentSession();
}

I don't want to change MyDAO (e.g. add @Transaction to the method, because it is used by other (old) code that is working

Similar questions say to add @Transaction to MyJdbcDAO but since this code worked without that it does not make sense I would need to add it now.

0

There are 0 answers