Hibernate Thread Hangs and never responds - java

I faced a weird issue and it is just like a dead-lock. When i call a dao method to save an entity into oracle db, hibernate never respond and thread never comes back. My aim is to save a row when exception is cached. However, Hibernate neither throws exception nor do its job. Just waiting forever(Thread has been waiting for 3 days). Is there any idea about the problem? what did i implement wrong?
Thread Dump is
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.FileDispatcherImpl.read0(FileDispatcherImpl.java:-1)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:197)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
- locked <0x9cfc> (a java.lang.Object)
at oracle.net.nt.TimeoutSocketChannel.read(TimeoutSocketChannel.java:144)
at oracle.net.ns.NIOHeader.readHeaderBuffer(NIOHeader.java:82)
at oracle.net.ns.NIOPacket.readFromSocketChannel(NIOPacket.java:139)
at oracle.net.ns.NIOPacket.readFromSocketChannel(NIOPacket.java:101)
at oracle.net.ns.NIONSDataChannel.readDataFromSocketChannel(NIONSDataChannel.java:80)
at oracle.jdbc.driver.T4CMAREngineNIO.prepareForReading(T4CMAREngineNIO.java:98)
at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalUB1(T4CMAREngineNIO.java:534)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:485)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:59)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:910)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1119)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3780)
at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1343)
at oracle.jdbc.driver.OraclePreparedStatement.executeLargeUpdate(OraclePreparedStatement.java:3865)
- locked <0x9cfd> (a oracle.jdbc.driver.T4CConnection)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3845)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1061)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:121)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:121)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3224)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3126)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3456)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:364)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:356)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:278)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:328)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:584)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:765)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:734)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:518)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671)
at com.xxx.yyy.zzz.PaymentTransactionService$$EnhancerBySpringCGLIB$$878a078.mergeWithNewTransaction(<generated>:-1)
at com.xxx.yyy.zzz.SavePaymentTransaction.process(SavePaymentTransaction.java:49)
class SavePaymentTransaction {
#Transactional
public void process(Entity e1){
try{
service.save(e1);// here throws exception
} catch(Exception e){
PaymentEntity pe = //createPaymentEntity
paymentTransactionService.mergeWithNewTransaction(pe);
// threads never comes back here and hangs when above line runs
}
}
}
class PaymentTransactionService {
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void mergeWithNewTransaction(PaymentEntity e1){
// this line is not shown in the thread dump
dao.save(e1);
}
}

Related

Hibernate code checks if session is closed before commiting txn but then complains session is closed

I am using Hibernate (with H2 database), sometimes if a task takes too long I cancel it so the session associate with the task becomes invalid. I have a method typically used in finally blocks and this ensure txn is committed and session closed but only if sessions till open, and not rolled back.
public static void commitAndClose(Session session)
{
try
{
if (session!=null && session.isOpen() && !session.getTransaction().wasRolledBack())
{
if(session.getTransaction().isActive())
{
session.getTransaction().commit();
}
}
}
catch(Exception ex)
{
Errors.addError(ex.getMessage());
}
finally
{
if (session!=null && session.isOpen())
{
HibernateUtil.closeSession(session);
}
}
}
Yet for some reason it is trying to commit the txn and then complains it was closed, even though the closed check immediately beforehand was okay.
Is this just a timing issue ?
org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:196)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:96)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3238)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3183)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3525)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:159)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at com.jthink.songkong.util.SessionUtil.commitAndClose(SessionUtil.java:32)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher1.doTask(MusicBrainzSongGroupMatcher1.java:448)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher.call(MusicBrainzSongGroupMatcher.java:469)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher1.call(MusicBrainzSongGroupMatcher1.java:83)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher1.call(MusicBrainzSongGroupMatcher1.java:37)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: org.h2.jdbc.JdbcSQLNonTransientException: The object is already closed [90007-199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:502)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:427)
at org.h2.message.DbException.get(DbException.java:205)
at org.h2.message.DbException.get(DbException.java:181)
at org.h2.message.DbException.get(DbException.java:170)
at org.h2.jdbc.JdbcConnection.checkClosed(JdbcConnection.java:1568)
at org.h2.jdbc.JdbcConnection.checkClosed(JdbcConnection.java:1547)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:347)
at jdk.internal.reflect.GeneratedMethodAccessor34.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at com.mchange.v2.c3p0.stmt.GooGooStatementCache$1StmtAcquireTask.run(GooGooStatementCache.java:546)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

Running transaction on different bean throws exception

I have asked this question and implemented the answer. It worked fine but now that I'm handling more data and it is not working as expected. Explaining:
I'm building integration with JMS. By the end of the integration process I must log the integration no matter what. To do so, I have build a #Service that saves a log in a new transaction. If I use the service, I'm getting an exception. If I execute the same logic of the service in the same bean it works fine. Let me show some code:
The listener
public class JMSListenerIntegration {
#Autowired
private IntegrationHandler integrationHandler;
#Autowired
private LogService logService;
#Autowired
private IntegrationLogRepository logRepository; // extends JpaRepository
#JmsListener(...)
public void onReceive(Message message) {
List<Dto> dtos = // Unmarshall the message
// A log for this integration already exists
// On receiving a message, it changes status from RUNNING to OK or NOK
IntegrationLog log = logRepository.findAlreadyExistingLog();
try {
// The integration handler persist 100+ records, each one in a new transaction
boolean success = integrationHandler.handle(dtos);
if (success)
log.setStatus("OK");
else
log.setStatus("NOK");
} catch (Exception e) {
log.setStatus("NOK");
} finally {
logService.save(log);
// this.saveLog(log); // THIS WORKS
}
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveLog(IntegrationLog log) {
logRepository.saveAndFlush(log);
}
}
LogService
#Service
public class LogService {
#Autowired
private IntegrationLogRepository logRepository;
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void save(IntegrationLog log) {
logRepository.saveAndFlush(log);
}
}
If I run the code using the saveLog() function defined on my JMSListenerIntegration it works fine. If, instead, I try to use my LogService class it does not work. I see on the log a hibernate query for selecting a log and then, after some good 20s, I get an error:
2019-01-02 20:21:35.649 WARN 21112 --- [ (self-tuning)'] onizationCallbackCoordinatorTrackingImpl : HHH000451: Transaction afterCompletion called by a background thread; delaying afterCompletion processing until the original thread can handle it. [status=4]
2019-01-02 20:21:35.652 WARN 21112 --- [enerContainer-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: null
2019-01-02 20:21:35.652 ERROR 21112 --- [enerContainer-1] o.h.engine.jdbc.spi.SqlExceptionHelper : The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 31 seconds
BEA1-36996D3224E23057A4BD]'. No further JDBC access is allowed within this transaction.
2019-01-02 20:21:35.657 INFO 21112 --- [enerContainer-1] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: could not load an entity: [com.example.models.IntegrationLog#6]
2019-01-02 20:21:35.692 WARN 21112 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Execution of JMS message listener failed, and no ErrorHandler has been set.
org.springframework.orm.jpa.JpaSystemException: could not load an entity: [com.example.models.IntegrationLog#6]; nested exception is org.hibernate.exception.GenericJDBCException: could not load an entity: [com.example.models.IntegrationLog#6]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:525) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:209) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.sun.proxy.$Proxy400.save(Unknown Source) ~[na:na]
at com.example.services.IntegrationLogService.save(IntegrationLogService.kt:20) ~[_wl_cls_gen.jar:na]
at com.example.services.IntegrationLogService$$FastClassBySpringCGLIB$$98a7fdd9.invoke(<generated>) ~[_wl_cls_gen.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:736) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.example.services.IntegrationLogService$$EnhancerBySpringCGLIB$$9eee6d68.save(<generated>) ~[_wl_cls_gen.jar:na]
at com.example.integrations.listeners.MalhaJmsListener.onReceive(MalhaJmsListener.kt:88) ~[_wl_cls_gen.jar:na]
at com.example.integrations.listeners.MalhaJmsListener$$FastClassBySpringCGLIB$$1357be2d.invoke(<generated>) ~[_wl_cls_gen.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:667) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.example.integrations.listeners.MalhaJmsListener$$EnhancerBySpringCGLIB$$c9de82e4.onReceive(<generated>) ~[_wl_cls_gen.jar:na]
at com.example.integrations.listeners.ListenersManager$startupListeners$1.onMessage(ListenersManager.kt:42) ~[_wl_cls_gen.jar:na]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:744) ~[spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:682) ~[spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:649) ~[spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:317) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:235) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1168) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1160) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1057) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_192]
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.example.models.IntegrationLog#6]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.loadEntity(Loader.java:2213) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4083) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1142) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.access$2600(SessionImpl.java:167) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2762) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2741) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:983) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:289) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:169) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:68) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:843) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:825) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:830) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161) ~[hibernate-entitymanager-5.1.0.Final.jar:5.1.0.Final]
at sun.reflect.GeneratedMethodAccessor252.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_192]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_192]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.sun.proxy.$Proxy386.merge(Unknown Source) ~[na:na]
at sun.reflect.GeneratedMethodAccessor252.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_192]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_192]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:300) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.sun.proxy.$Proxy386.merge(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:511) ~[spring-data-jpa-1.11.14.RELEASE.jar:na]
at sun.reflect.GeneratedMethodAccessor254.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_192]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_192]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:515) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:500) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:477) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
... 35 common frames omitted
Caused by: java.sql.SQLException: The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 30 seconds
BEA1-01E60652F53A3057A4BD]'. No further JDBC access is allowed within this transaction.
at weblogic.jdbc.wrapper.JTSConnection.checkIfRolledBack(JTSConnection.java:202) ~[weblogic.server.merged.jar:12.1.3.0.0]
at weblogic.jdbc.wrapper.JTSConnection.checkConnection(JTSConnection.java:220) ~[weblogic.server.merged.jar:12.1.3.0.0]
at weblogic.jdbc.wrapper.ResultSet.preInvocationHandler(ResultSet.java:95) ~[weblogic.server.merged.jar:12.1.3.0.0]
at weblogic.jdbc.wrapper.ResultSet_weblogic_jdbc_sqlserverbase_ddeb.next(Unknown Source) ~[weblogic.server.merged.jar:12.1.3.0.0]
at org.hibernate.loader.Loader.processResultSet(Loader.java:974) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:936) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:312) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.loadEntity(Loader.java:2209) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
... 81 common frames omitted
Any ideas on why this is happening?
Thanks,
EDIT
Following the comments suggestion I have changed my LogService to look like:
#Service
public class LogService {
#Autowired
private IntegrationLogRepository logRepository;
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void save(IntegrationLog plainLog) {
IntegrationLog log = logRepository.findOne(plainLog.getId());
log.setStatus(plainLog.getStatus());
log.setFoo(plainLog.getFoo());
// ...
logRepository.saveAndFlush(log);
}
}
And I still get the same error. And I start to think it is related to the previous operations done on integrationHandler.handle(dtos). In this method, I persist a lot of records. The logic looks like:
public boolean handle(List<Dto> dtos) {
boolean result = true;
for (Dto dto in dtos) {
try {
Foo foo = new Foo();
foo.setProp1(dto.getProp1());
foo.setProp2(dto.getProp2());
saveFoo(foo);
} catch (Exception e) {
logger.error(e.getMessage());
result = false;
}
}
return result;
}
// Now I know this is not running in its own transaction, right?
#Transactional(propagation = Propagation.REQUIRES_NEW)
public saveFoo(Foo foo) {
fooRepository.save(foo);
}
If I don't call the handle() method (so the persist operations are not performed) the LogService works just fine. I can only imagine the transaction for saving the Foo's are taking too long and the transaction for findOne is gettint timed out (can't find a reason why) giving the could not load an entity (I even tried calling findOne(6) which is a valid ID in my database). Maybe this is not the right way to persist the data...? Really lost here guys. Any help is appreciated :/

Is there anything special about configuring the use of multiple buckets in a spring-data-couchbase Java application?

I'm working on a Java-based spring-data-couchbase application that connects to multiple buckets to do its work. We are seeing TimeoutExceptions being thrown when trying to retrieve documents from the buckets with a stack trace like this:
10-17-2016 14:28:10 (WebContainer : 9) ERROR [com.cars.ss.cp.resources.ProfileResource] - [RESOURCE] [ERROR] Service com.sun.proxy.$Proxy195.getConsumerProfileSummaryVersion throws org.springframework.dao.QueryTimeoutException.
org.springframework.dao.QueryTimeoutException: java.util.concurrent.TimeoutException; nested exception is java.lang.RuntimeException: java.util.concurrent.TimeoutException
at org.springframework.data.couchbase.core.CouchbaseExceptionTranslator.translateExceptionIfPossible(CouchbaseExceptionTranslator.java:122)
at org.springframework.data.couchbase.core.CouchbaseTemplate.execute(CouchbaseTemplate.java:500)
at org.springframework.data.couchbase.core.CouchbaseTemplate.exists(CouchbaseTemplate.java:464)
at org.springframework.data.couchbase.repository.support.SimpleCouchbaseRepository.exists(SimpleCouchbaseRepository.java:110)
at sun.reflect.GeneratedMethodAccessor241.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.couchbase.repository.support.ViewPostProcessor$ViewInterceptor.invoke(ViewPostProcessor.java:87)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy148.exists(Unknown Source)
at sun.reflect.GeneratedMethodAccessor240.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy174.exists(Unknown Source)
at com.cars.ss.cp.service.impl.ProfilePhotoService.findByConsumerId(ProfilePhotoService.java:43)
at com.cars.ss.cp.dao.impl.ConsumerAccountDAO.findConsumerAccountByPartyId(ConsumerAccountDAO.java:77)
at sun.reflect.GeneratedMethodAccessor287.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy186.findConsumerAccountByPartyId(Unknown Source)
at com.cars.ss.cp.service.impl.ProfileService.getBOConsumerProfileVersion(ProfileService.java:235)
at com.cars.ss.cp.service.impl.ProfileService.getProfileSummaryByPersonPartyId(ProfileService.java:489)
at com.cars.ss.cp.service.impl.ProfileService.getProfileSummaryByConsumerId(ProfileService.java:479)
at sun.reflect.GeneratedMethodAccessor286.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy195.getProfileSummaryByConsumerId(Unknown Source)
at com.cars.ss.cp.resources.ProfileResource.getSummaryReadByConsumerId(ProfileResource.java:362)
at com.cars.ss.cp.resources.ProfileResource.getConsumerProfileSummaryVersion(ProfileResource.java:320)
at com.cars.ss.cp.resources.ProfileResource.getConsumerProfile(ProfileResource.java:252)
at sun.reflect.GeneratedMethodAccessor261.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.apache.wink.server.internal.handlers.InvokeMethodHandler.handleRequest(InvokeMethodHandler.java:63)
...
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1225)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:775)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:457)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1032)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:908)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:195)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:283)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture$1.run(AsyncChannelFuture.java:205)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1815)
Caused by: java.lang.RuntimeException: java.util.concurrent.TimeoutException
at com.couchbase.client.java.util.Blocking.blockForSingle(Blocking.java:75)
at com.couchbase.client.java.CouchbaseBucket.exists(CouchbaseBucket.java:159)
at com.couchbase.client.java.CouchbaseBucket.exists(CouchbaseBucket.java:154)
at org.springframework.data.couchbase.core.CouchbaseTemplate$5.doInBucket(CouchbaseTemplate.java:467)
at org.springframework.data.couchbase.core.CouchbaseTemplate$5.doInBucket(CouchbaseTemplate.java:464)
at org.springframework.data.couchbase.core.CouchbaseTemplate.execute(CouchbaseTemplate.java:497)
... 120 more
Caused by: java.util.concurrent.TimeoutException
... 126 more
I configured my Couchbase configuration class with multiple buckets like this:
#EnableCouchbaseRepositories(basePackages = { "com.cars.ss.cp.nosql.repository" })
#Configuration
public class CouchbaseConfiguration extends AbstractCouchbaseConfiguration {
private static Logger logger = Logger.getLogger(CouchbaseConfiguration.class);
private static final long TIMEOUT_IN_SECONDS = 10;
#Autowired
#Qualifier("propertyService")
private PropertyService propertyService;
#Bean(name = { "defaultBucket" })
public Bucket defaultBucket() throws Exception {
return couchbaseCluster().openBucket(getBucketName());
}
#Override
protected List<String> getBootstrapHosts() {
String rawPropertyValue = this.propertyService.getPropertyValue(COUCHBASE_HOSTS);
if (StringUtils.isNotBlank(rawPropertyValue)) {
StringTokenizer st = new StringTokenizer(rawPropertyValue, ",");
List<String> returnValue = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens()) {
returnValue.add(st.nextToken().trim());
}
return returnValue;
}
logger.error("Unable to process the couchbaseHosts property. Property value: " + rawPropertyValue);
return Collections.emptyList();
}
#Override
protected String getBucketName() {
return this.propertyService.getPropertyValue(COUCHBASE_BUCKET);
}
#Override
protected String getBucketPassword() {
return null;
}
#Override
protected CouchbaseEnvironment getEnvironment() {
return DefaultCouchbaseEnvironment.builder().connectTimeout(TimeUnit.SECONDS.toMillis(TIMEOUT_IN_SECONDS)).kvTimeout(TimeUnit.SECONDS.toMillis(TIMEOUT_IN_SECONDS)).build();
}
#Bean
public Bucket consumerProfileBucket() throws Exception {
return couchbaseCluster().openBucket(this.propertyService.getPropertyValue(CONSUMER_PROFILE_BUCKET), this.propertyService.getPropertyValue(CONSUMER_PROFILE_BUCKET_PASSWORD));
}
#Bean
public CouchbaseTemplate consumerProfileTemplate() throws Exception {
CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), consumerProfileBucket(), mappingCouchbaseConverter(), translationService());
template.setDefaultConsistency(getDefaultConsistency());
return template;
}
#Override
protected void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) {
try {
baseMapping.mapEntity(OwnedVehicle.class, consumerProfileTemplate());
baseMapping.mapEntity(ProfilePhoto.class, consumerProfileTemplate());
} catch (Exception e) {
logger.error("Errors encountered during configuration. Exception: " + e);
}
}
}
I originally didn't have the "getEnvironment" method overridden. Based on some recommendations that I saw online, I overrode that method and increased both the connection timeout and key-value timeout to 10 seconds to see if that might help, but it did not. When I increased the timeout from the defaults to 10 seconds, the timeout of the document retrieval became exactly 10 seconds. The TimeoutException is occurring against a document that is trying to be retrieved using the document's key.
The application has the following specifications:
* Java version: 1.7
* spring-data-couchbase version: 2.1.1.RELEASE
* java-client version: 2.2.5
* IBM WebSphere version: 8.5
Is there something obvious that I am missing in the way I have things configured? Are there any other ideas out there of things that I can look at to repair this problem?
10/24/2016 - Added a thread analysis image from the javacore:
thread analysis image from javacore

I'm getting ResourceException: Transaction is not active

I'm using Jboss Version 5.2.0.GA and I'm getting Transaction is not active when updating the status of a record in DB using hql.
DB connections are not exhausted, other requests are fulfilled by DB, I believe transaction is expired!
if 300 is increased in transaction-jboss-beans.xml will it help ?
2016-05-23 10:37:11,722 - ERROR - TestDAO.java : updateRecord (490) - updateRecord() Exception Message Cannot open connection
org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.AbstractBatcher.prepareSelectStatement(AbstractBatcher.java:145)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1034)
at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:268)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:212)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:534)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:102)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:537)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:529)
at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:241)
at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:302)
at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:246)
at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:195)
at org.hibernate.engine.Cascade.cascade(Cascade.java:154)
at org.hibernate.engine.Cascade.cascade(Cascade.java:121)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.cascadeOnUpdate(DefaultSaveOrUpdateEventListener.java:379)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:351)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:245)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:594)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:582)
at com.abc.xyz.dao.SendSmsDAO.updateSendSms(SendSmsDAO.java:479)
at com.abc.xyz.transport.smpp.SMPPTransport.submitShortMessages(SMPPTransport.java:809)
at com.abc.xyz.transport.smpp.SMPPTransport.submit(SMPPTransport.java:647)
at com.abc.xyz.listeners.SendSmsMDB.onMessage(SendSmsMDB.java:202)
at sun.reflect.GeneratedMethodAccessor845.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.invocation.Invocation.performCall(Invocation.java:386)
at org.jboss.ejb.MessageDrivenContainer$ContainerInterceptor.invoke(MessageDrivenContainer.java:518)
at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:156)
at org.jboss.ejb.plugins.MessageDrivenInstanceInterceptor.invoke(MessageDrivenInstanceInterceptor.java:115)
at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:63)
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:121)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:350)
at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:181)
at org.jboss.ejb.plugins.RunAsSecurityInterceptor.process(RunAsSecurityInterceptor.java:139)
at org.jboss.ejb.plugins.RunAsSecurityInterceptor.invoke(RunAsSecurityInterceptor.java:103)
at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:205)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:138)
at org.jboss.ejb.MessageDrivenContainer.internalInvoke(MessageDrivenContainer.java:420)
at org.jboss.ejb.Container.invoke(Container.java:1092)
at sun.reflect.GeneratedMethodAccessor786.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at org.jboss.invocation.local.LocalInvoker$MBeanServerAction.invoke(LocalInvoker.java:169)
at org.jboss.invocation.local.LocalInvoker.invoke(LocalInvoker.java:118)
at org.jboss.invocation.InvokerInterceptor.invokeLocal(InvokerInterceptor.java:209)
at org.jboss.invocation.InvokerInterceptor.invoke(InvokerInterceptor.java:195)
at org.jboss.proxy.TransactionInterceptor.invoke(TransactionInterceptor.java:61)
at org.jboss.ejb.plugins.inflow.MessageEndpointInterceptor.delivery(MessageEndpointInterceptor.java:249)
at org.jboss.ejb.plugins.inflow.MessageEndpointInterceptor.invoke(MessageEndpointInterceptor.java:128)
at org.jboss.proxy.ClientMethodInterceptor.invoke(ClientMethodInterceptor.java:74)
at org.jboss.proxy.ClientContainer.invoke(ClientContainer.java:101)
at $Proxy1791.onMessage(Unknown Source)
at org.jboss.resource.adapter.jms.inflow.JmsServerSession.onMessage(JmsServerSession.java:179)
at org.jboss.jms.client.container.ClientConsumer.callOnMessageStatic(ClientConsumer.java:167)
at org.jboss.jms.client.container.SessionAspect.handleRun(SessionAspect.java:879)
at org.jboss.aop.advice.org.jboss.jms.client.container.SessionAspect_z_handleRun_1017119892.invoke(SessionAspect_z_handleRun_1017119892.java)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102)
at org.jboss.jms.client.container.ClosedInterceptor.invoke(ClosedInterceptor.java:172)
at org.jboss.aop.advice.PerInstanceInterceptor.invoke(PerInstanceInterceptor.java:86)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102)
at org.jboss.jms.client.delegate.ClientSessionDelegate.run(ClientSessionDelegate.java)
at org.jboss.jms.client.JBossSession.run(JBossSession.java:199)
at org.jboss.resource.adapter.jms.inflow.JmsServerSession.run(JmsServerSession.java:236)
at org.jboss.resource.work.WorkWrapper.execute(WorkWrapper.java:205)
at org.jboss.util.threadpool.BasicTaskWrapper.run(BasicTaskWrapper.java:260)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.jboss.util.NestedSQLException: Transaction is not active: tx=TransactionImple < ac, BasicAction: a1c162a:994a:5742b99a:169b status: ActionStatus.ABORTED >; - nested throwable: (javax.resource.ResourceException: Transaction is not active: tx=TransactionImple < ac, BasicAction: a1c162a:994a:5742b99a:169b status: ActionStatus.ABORTED >)
at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:95)
at org.hibernate.connection.DatasourceConnectionProvider.getConnection(DatasourceConnectionProvider.java:91)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
... 78 more
Caused by: javax.resource.ResourceException: Transaction is not active: tx=TransactionImple < ac, BasicAction: a1c162a:994a:5742b99a:169b status: ActionStatus.ABORTED >
at org.jboss.resource.connectionmanager.TxConnectionManager.getManagedConnection(TxConnectionManager.java:413)
at org.jboss.resource.connectionmanager.BaseConnectionManager2.allocateConnection(BaseConnectionManager2.java:496)
at org.jboss.resource.connectionmanager.BaseConnectionManager2$ConnectionManagerProxy.allocateConnection(BaseConnectionManager2.java:941)
at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:89)
... 80 more
Regards,
Nithesh
Could you post your line code? I dont know if you are using annotation to controls the transactions so maybe using entityManager.getTransaction.begin() before you do the merge could solve the problem.
I'm not using Jboss transactions, I'm using hibernate transactions, please find the code below.
public void persistStatus(Status transientInstance){
logger.debug("persisting into DB");
org.hibernate.Transaction transaction = null;
try
{
openSession();
transaction = session.beginTransaction();
session.persist(transientInstance);
transaction.commit();
logger.debug("persist successfully ");
}
catch (HibernateException re){
logger.error("Exception while inserting status "+re);
if(transaction!=null && transaction.isActive())
transaction.rollback();
closeActiveSession();
throw re;
}finally{
if (session != null && session.isOpen()) {
session.clear();
session.close();
}
}
}
I think Jboss internally handles transactions ?

Spring Data Jpa repository in spring batch tasklet throws TransactionRequiredException

I'm having problems using a Spring Data Jpa repository inside a Spring Batch tasklet.
I'd expect to have a valid hibernate transaction in the MyOrderTasklet's execute method using the myTransactionManager that is configured for this step. But as soon as flush() is called or if the execute method is left (without explicitly calling flush()). I get a
TransactionRequiredException"no transaction is in progress".
When debugging I see that a transaction gets created by spring batch before entering the tasklet's execute method and that a valid hibernateTransaction is created and put in the org.hibernate.jdbc.JDBCContext instance by calling getJpaDialect().beginTransaction() in org.springframework.orm.jpa.JpaTransactionManager#doBegin().
When methods of the orderRepository are called, I see that the call to AbstractPlatformTransactionManager#getTransaction finds an existing transaction and calls handleExistingTransaction. But later on org.hibernate.ejb.AbstractEntityManagerImpl#isTransactionInProgress returns false because no hibernateSession can be found.
I see that different Hibernate sessions and EntityManagers are created for transaction around the tasklet's execute method and for the calls to the repository. The outer hibernate transaction which is bound to the outer hibernate session can't be found by the inner hibernate session.
Any ideas how to solve this? How can the same hibernate session be used for the tasklet's execute method and the calls to the repository? Can the hibernateTemplate maybe be propagated to other sessions somehow?
Here's some code extract to show my setup:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackageClasses = MyRepositoryConfig.class)
#ComponentScan(basePackageClasses=MyRepositoryConfig.class)
public class MyRepositoryConfig {
#Autowired
private InfrastructureConfiguration infrastructureConfiguration;
#Bean
public EntityManagerFactory entityManagerFactory() throws SQLException {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(infrastructureConfiguration.hibernateJpaVendorAdapter());
factory.setPackagesToScan("com.example.model");
factory.setDataSource(infrastructureConfiguration.dataSource());
if (StringUtils.hasText(infrastructureConfiguration.getSchema())) {
factory.getJpaPropertyMap().put("hibernate.default_schema", infrastructureConfiguration.getSchema());
}
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean(name= { "transactionManager", "myTransactionManager"})
public PlatformTransactionManager transactionManager() throws SQLException {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
#Bean
public MyRepositoryService myRepositoryService() {
return new myRepositoryServiceImpl();
}
}
#Configuration
public class DefaultInfrastructureConfiguration implements InfrastructureConfiguration {
#Value("${my.schema:MYSCHEMA}")
private String defaultSchema;
#Value("${novis.jdbc.url:jdbc:oracle:thin:#//example.com/example}")
private String jdbcUrl;
#Value("${novis.jdbc.username:scott}")
private String jdbcUsername;
#Value("${novis.jdbc.password:tiger}")
private String jdbcPassword;
#Value("${novis.jdbc.driverClassName:oracle.jdbc.driver.OracleDriver}")
private String jdbcDriverClassName;
#Value("${novis.hibernate.database:ORACLE}")
private String hibernateDatabase;
#Bean
#Override
public DataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriverClassName);
ds.setUrl(jdbcUrl);
ds.setUsername(jdbcUsername);
ds.setPassword(jdbcPassword);
ds.setTestWhileIdle(true);
ds.setValidationQuery("SELECT 1 FROM DUAL");
return ds;
}
#Override
public HibernateJpaVendorAdapter hibernateJpaVendorAdapter() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setDatabase(Database.valueOf(Database.class, hibernateDatabase));
return vendorAdapter;
}
#Override
public String getSchema() {
return defaultSchema;
}
}
#Configuration
#Import(MyRepositoryConfig.class)
public class OrderManagerConfig {
#Autowired
#Qualifier("myTransactionManager")
private PlatformTransactionManager myTransactionManager;
....
#Bean
public Tasklet MyOrderTasklet() {
return new MyOrderTasklet();
}
....
#Bean
public Step processMyOrderErrorsStep() {
return steps.get("processMyOrderErrorsStep").
transactionManager(myTransactionManager).
tasklet(myOrderProcessor()).
listener(stepExecutionLoggerListener()).
build();
}
....
}
public class MyOrderTasklet implements Tasklet {
#Autowired
private OrderRepository orderRepository;
#Autowired
private PlatformTransactionManager myTransactionManager;
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
for (Order order : orderRepository.findByErrorIsNotNullAndErrorHandledFalse()) {
// Handle the error...
order.setErrorHandled(true);
orderRepository.saveAndFlush(order);
}
return RepeatStatus.FINISHED;
}
}
Exception:
03 Sep 2014 09:53:39:902 ERROR AbstractStep:225 - Encountered an error executing step processMyOrderErrorsStep in job processMyOrderErrors
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:959) ~[hibernate-entitymanager-3.6.10.Final.jar:3.6.10.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:342) ~[spring-orm-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at com.sun.proxy.$Proxy153.flush(Unknown Source) ~[?:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:289) ~[spring-orm-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at com.sun.proxy.$Proxy153.flush(Unknown Source) ~[?:?]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.flush(SimpleJpaRepository.java:436) ~[spring-data-jpa-1.6.1.RELEASE.jar:?]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.saveAndFlush(SimpleJpaRepository.java:404) ~[spring-data-jpa-1.6.1.RELEASE.jar:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405) ~[spring-data-commons-1.8.1.RELEASE.jar:?]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390) ~[spring-data-commons-1.8.1.RELEASE.jar:?]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344) ~[spring-data-commons-1.8.1.RELEASE.jar:?]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111) ~[spring-data-jpa-1.6.1.RELEASE.jar:?]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at com.sun.proxy.$Proxy198.saveAndFlush(Unknown Source) ~[?:?]
at ch.local.ordermanager.MyOrderTasklet.execute(MyOrderTasklet.java:41) ~[classes/:?]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:77) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368) ~[spring-batch-infrastructure-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:198) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:386) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:304) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobOperator.start(SimpleJobOperator.java:314) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
at ch.local.batchmanager.BatchJobRunner.runJob(BatchJobRunner.java:20) [classes/:?]
at ch.local.batchmanager.BatchManager.run(BatchManager.java:30) [classes/:?]
at ch.local.common.base.AbstractBatchApplication.execute(AbstractBatchApplication.java:38) [classes/:?]
at ch.local.batchmanager.BatchManager.main(BatchManager.java:9) [classes/:?]
I suspect the following piece of code:
#Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
Usually you don't configure an entityManager singleton, you let Spring decide when to create a new instance at transaction boundary.
The entity manager is usually being inserted using:
#PersistenceContext
EntityManager entityManager;
Even if you don't declare such bean, Spring will still create one and will provide you the one that's suitable for your current running transaction.
Using a singleton EntityManager is problematic, since the EntityManager is not thread-safe and reusing it without clearing might also lead to memory leaks and stale entity versions.
Although I defined the hibernate verison in the pom.xml to be 4.3.5, another library in our project has a dependency to hibernate 3.6.10, which was then used (and I did not notice). The error disappeared after getting rid of Hibernate 3 and using the latest hibernate 4 version (4.3.5 at the moment).

Categories