Problems with WebSphereUowTransactionManager in Spring MDP - spring

I am having trouble setting up a MDP in Spring 3.0.4 in WebSphere 7.0 using the WebSphereUowTransactionManager.
If I don't use WebSphereUowTransactionManager, it works just fine. Without it, I won't have any XA-action on errors, so I think I really need that.
Here is what happens on the server:
[9/22/10 16:26:35:093 CDT] 00000070 SystemOut O 16:26:35.093 [WorkManager.DefaultWorkManager : 4] DEBUG o.s.t.j.WebSphereUowTransactionManager - Creating new transaction with name [jmsContainer]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
[9/22/10 16:26:36:140 CDT] 00000070 SystemOut O 16:26:36.140 [WorkManager.DefaultWorkManager : 4] DEBUG o.s.j.l.DefaultMessageListenerContainer - Initiating transaction rollback on listener exception
java.lang.NullPointerException: null
at org.springframework.jms.listener.AbstractMessageListenerContainer.commitIfNecessary(AbstractMessageListenerContainer.java:571) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:354) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:241) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1056) [org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:952) [org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.scheduling.commonj.DelegatingWork.run(DelegatingWork.java:61) [org.springframework.context.support-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at com.ibm.ws.asynchbeans.J2EEContext.run(J2EEContext.java:1150) [com.ibm.ws.runtime.jar:na]
at com.ibm.ws.asynchbeans.WorkWithExecutionContextImpl.go(WorkWithExecutionContextImpl.java:199) [com.ibm.ws.runtime.jar:na]
at com.ibm.ws.asynchbeans.CJWorkItemImpl.run(CJWorkItemImpl.java:188) [com.ibm.ws.runtime.jar:na]
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550) [com.ibm.ws.runtime.jar:na]
[9/22/10 16:26:36:140 CDT] 00000070 SystemOut O 16:26:36.140 [WorkManager.DefaultWorkManager : 4] DEBUG o.s.t.j.WebSphereUowTransactionManager - Initiating transaction rollback
[9/22/10 16:26:41:140 CDT] 00000070 SystemOut O 16:26:41.140 [WorkManager.DefaultWorkManager : 4] WARN o.s.j.l.DefaultMessageListenerContainer - Setup of JMS message listener invoker failed for destination 'queue://testQ?busName=WorkManagementBus' - trying to recover. Cause: null
java.lang.NullPointerException: null
at org.springframework.jms.listener.AbstractMessageListenerContainer.commitIfNecessary(AbstractMessageListenerContainer.java:571) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:354) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:241) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1056) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:952) ~[org.springframework.jms-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at org.springframework.scheduling.commonj.DelegatingWork.run(DelegatingWork.java:61) [org.springframework.context.support-3.0.4.RELEASE.jar:3.0.4.RELEASE]
at com.ibm.ws.asynchbeans.J2EEContext.run(J2EEContext.java:1150) [com.ibm.ws.runtime.jar:na]
at com.ibm.ws.asynchbeans.WorkWithExecutionContextImpl.go(WorkWithExecutionContextImpl.java:199) [com.ibm.ws.runtime.jar:na]
at com.ibm.ws.asynchbeans.CJWorkItemImpl.run(CJWorkItemImpl.java:188) [com.ibm.ws.runtime.jar:na]
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550) [com.ibm.ws.runtime.jar:na]
[9/22/10 16:26:41:140 CDT] 00000070 SystemOut O 16:26:41.140 [WorkManager.DefaultWorkManager : 4] INFO o.s.j.l.DefaultMessageListenerContainer - Successfully refreshed JMS Connection
Here is my applicationContext.xml file:
<bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager" />
<bean id="myTaskExecutor" class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor">
<property name="workManagerName" value="wm/default" />
</bean>
<jee:jndi-lookup id="queue" jndi-name="jms/queue" resource-ref="true" proxy-interface="javax.jms.Queue"></jee:jndi-lookup>
<jee:jndi-lookup id="connectionFactory" jndi-name="jms/ConnectionFactory" resource-ref="true"></jee:jndi-lookup>
<bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"></property>
<property name="destination" ref="queue"></property>
<property name="messageListener" ref="testMessageListener"></property>
<property name="taskExecutor" ref="myTaskExecutor"></property>
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<bean id="testMessageListener" class="navy.jmsey.TestMessageListener" />
I can't figure out why this isn't working. I think I'm doing everything I'm supposed to. I followed the directions in http://www.ibm.com/developerworks/websphere/techjournal/0609_alcott/0609_alcott.html.
Anyone seen this or see what I'm doing wrong?
Thanks.
Update:
I've tried doing a EJB3 Message-driven Bean and that works as expected, on exception it gets redelivered up to 5 times. The problem with that, is the semantics for dependency injection and transaction containment just got more complicated. I'm pretty sure this isn't how I want to go.
Update:
I asked WebSphere support, but they turned me away. As expected.

It seems there is a JIRA on this here.
The person says she managed to get it working by replacing
commitIfNecessary(session, message); // line 354
with
commitIfNecessary(sessionToUse, message);
in the AbstractMessageListenerContainer.java class.

Related

How to fix NullPointerException when getting current Hibernate Session

In my WebSphere 9 application thats built on Spring 5 / Hibernate 5 I get this error when retrieving the current Hibernate session with org.hibernate.SessionFactory.getCurrentSession():
[9/26/19 10:41:22:405 CEST] 0001f184 DefaultMessag W org.springframework.jms.listener.AbstractMessageListenerContainer invokeErrorHandler Execution of JMS message listener failed, and no ErrorHandler has been set.
java.lang.IllegalStateException: An exception occured during the cumulation before the processingId could be created: java.lang.NullPointerException
at com.tsystems.cc4.service.cumulation.CumulationHandlerImpl.cumulate(CumulationHandlerImpl.java:138)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:508)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at com.tsystems.cc4.service.cumulation.NonClosingOpenSessionInterceptor.invoke(NonClosingOpenSessionInterceptor.java:40)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy184.cumulate(Unknown Source)
at com.tsystems.cc4.service.cumulation.ScheduleCommandHandler.invoke(ScheduleCommandHandler.java:62)
at com.tsystems.cc4.service.invocation.listener.InvocationWrapperListener.onMessage(InvocationWrapperListener.java:128)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:736)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:696)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:674)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:318)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:245)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1189)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1081)
at javax.enterprise.concurrent.ManagedExecutors$RunnableAdapter.run(ManagedExecutors.java:211)
at com.ibm.ws.asynchbeans.SubmittedTask.run(SubmittedTask.java:711)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1909)
Caused by: java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:508)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:282)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:266)
at org.springframework.orm.hibernate5.SessionFactoryUtils.getFlushMode(SessionFactoryUtils.java:125)
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:100)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:456)
at com.tsystems.cc4.control.dao.impl.AbstractHibernateDAO.getSession(AbstractHibernateDAO.java:51)
at com.tsystems.cc4.control.dao.impl.GenericCrudDAOImpl.readInReadOnlyMode(GenericCrudDAOImpl.java:107)
at com.tsystems.cc4.service.cumulation.CumulationHandlerImpl.cumulate(CumulationHandlerImpl.java:120)
... 23 more
[9/26/19 10:41:22:415 CEST] 0001f184 TransactionSy E org.springframework.transaction.support.TransactionSynchronizationUtils triggerBeforeCompletion TransactionSynchronization.beforeCompletion threw exception
java.lang.NullPointerException
at org.springframework.orm.hibernate5.SpringSessionSynchronization.beforeCompletion(SpringSessionSynchronization.java:110)
at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCompletion(TransactionSynchronizationUtils.java:107)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCompletion(AbstractPlatformTransactionManager.java:935)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:826)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:702)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:251)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1189)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1081)
at javax.enterprise.concurrent.ManagedExecutors$RunnableAdapter.run(ManagedExecutors.java:211)
at com.ibm.ws.asynchbeans.SubmittedTask.run(SubmittedTask.java:711)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1909)
The application code successfully ran on Spring 4.3.14.RELEASE + Hibernate 4.2.21.Final.
The problem occurs since we upgraded to Spring 5.1.1.RELEASE + Hibernate 5.2.9.Final.
Spring configuration before (Spring 4.3.14.RELEASE + Hibernate 4.2.21.Final):
<bean id="cumulationConfigDAO" class="com.tsystems.cc4.control.dao.impl.GenericCrudDAOImpl">
<constructor-arg value="com.tsystems.cc4.control.model.cumulation.CumulationConfig" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="controlDataSource" />
<property name="packagesToScan" value="com.tsystems.cc4.control.model" />
<property name="hibernateProperties">
<value>
hibernate.default_schema=CC4
hibernate.dialect=org.hibernate.dialect.${jdbc.dialect}Dialect
org.jboss.logging.provider=slf4j
${hib_tx_platform}
${hib_tx_factory}
</value>
</property>
</bean>
Properties:
# Settings for DB2
jdbc.dialect=DB2
# Hibernate JTA Transaction Platform configuration
hib_tx_platform=hibernate.transaction.jta.platform=org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform
hib_tx_factory=hibernate.transaction.factory_class=org.hibernate.transaction.CMTTransactionFactory
Spring configuration after (Spring 5.1.1.RELEASE + Hibernate 5.2.9.Final):
<bean id="cumulationConfigDAO" class="com.tsystems.cc4.control.dao.impl.GenericCrudDAOImpl">
<constructor-arg name="entityClass" value="com.tsystems.cc4.control.model.cumulation.CumulationConfig" />
<constructor-arg name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="controlDataSource" />
<property name="packagesToScan" value="com.tsystems.cc4.control.model" />
<property name="hibernateProperties">
<value>
hibernate.default_schema=CC4
hibernate.dialect=org.hibernate.dialect.${jdbc.dialect}Dialect
org.jboss.logging.provider=slf4j
${hib_tx_platform}
${hib_tx_factory}
hibernate.id.new_generator_mappings=false
hibernate.allow_update_outside_transaction=true
</value>
</property>
</bean>
Properties:
# Settings for DB2
jdbc.dialect=DB2
# Hibernate JTA Transaction Platform configuration
hib_tx_platform=hibernate.transaction.jta.platform=org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform
hib_tx_factory=hibernate.transaction.factory_class=org.hibernate.transaction.CMTTransactionFactory
Solved. The reason for the problem was some specialized stuff we had built in former times to work around problems after migrating from Hibernate 3 to 4. The Spring context contained non-standard stuff like this:
<!-- The Hibernate interceptor, which takes care of opening and closing
hibernate session around method calls. -->
<bean id="hibernateInterceptor"
class="com.tsystems.cc4.service.cumulation.NonClosingOpenSessionInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- A proxy with the hibernate interceptor wired in so it can access
the persistent context -->
<bean id="cumulationHandler" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="com.tsystems.cc4.service.cumulation.CumulationHandlerImpl" />
</property>
<property name="proxyInterfaces">
<value>com.tsystems.cc4.service.cumulation.CumulationHandler</value>
</property>
<property name="interceptorNames">
<value>hibernateInterceptor</value>
</property>
</bean>
Removing those beans solved the problem.
Here's from the class comment of NonClosingOpenSessionInterceptor: "Specialized version of org.springframework.orm.hibernate4.support.OpenSessionInterceptor that - if necessary - opens a Hibernate session and registers it with Spring's TransactionSynchronizationManager without closing it after the method call. This is necessary if closing the Hibernate session should occur through the transaction manager during transaction completion.
This class has been created to work around the "org.hibernate.SessionException: Session is closed!" problem that occurs when using org.springframework.orm.hibernate4.support.OpenSessionInterceptor in conjunction with Spring's PlatformTransactionManager."
used #Transactional
to either service Method or Dao Method?

Spring singleton scope isn't working in spring-integration application

I have a spring-integration application with the following configuration :
<beans:bean id="customMessageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer" scope = "singleton">
<beans:property name="errorHandler" ref="customErrorHandler"/>
<beans:property name="connectionFactory" ref="connectionFactory" />
<beans:property name="destination" ref="jmsInputQueueXssl" />
<beans:property name="sessionTransacted" value="true" />
<beans:property name="maxConcurrentConsumers" value="1" />
<beans:property name="concurrentConsumers" value="1" />
<beans:property name="receiveTimeout" value="5000" />
<beans:property name="recoveryInterval" value="60000" />
<beans:property name="autoStartup" value="true" />
<beans:property name="exposeListenerSession" value="false" />
<beans:property name="subscriptionDurable" value="true" />
<beans:property name="durableSubscriptionName" value="${ibm.jms.subscription.id1}" />
<beans:property name="backOff" ref="myBackoff" />
</beans:bean>
<beans:bean id="myBackoff" class="c.h.i.c.d.x.j.MyFixedBackOff">
<beans:constructor-arg index="0" value="5000"/>
<beans:constructor-arg index="1" value="5"/>
</beans:bean>
<!-- Custom error handler -->
<beans:bean id="customErrorHandler" class="c.h.i.c.d.x.j.XsslCustomErrorHandler" />
<beans:beans profile="env">
<jms:message-driven-channel-adapter
id="jmsInboundAdapterXssl" channel="channel2"
acknowledge="transacted" error-channel="errorChannel"
container="customMessageListenerContainer"/>
</beans:beans>
However, it seems that there are several instances of that class customMessageListenerContainer if I read the logs :
2019-05-10 17:54:39,783 INFO [main] o.s.i.e.SourcePollingChannelAdapter [AbstractEndpoint.java:97] started org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean#0
2019-05-10 17:54:39,783 INFO [main] o.s.c.s.DefaultLifecycleProcessor [DefaultLifecycleProcessor.java:341] Starting beans in phase 2147483647
2019-05-10 17:54:39,924 INFO [customMessageListenerContainer-1] c.h.i.c.d.x.j.MyFixedBackOff [MyFixedBackOff.java:115] MyFixedBackOff currentAttempts = 0
2019-05-10 17:54:44,930 WARN [customMessageListenerContainer-1] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:871] Setup of JMS message listener invoker failed for destination 'queue:///CT_XSSL.CT_CPMX.MRZC_DGRM.0013' - trying to recover. Cause: JMSWMQ2008: Failed to open MQ queue 'CT_XSSL.CT_CPMX.MRZC_DGRM.0013'.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2085' ('MQRC_UNKNOWN_OBJECT_NAME').
2019-05-10 17:54:44,930 INFO [customMessageListenerContainer-1] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:921] Successfully refreshed JMS Connection
2019-05-10 17:54:44,930 INFO [customMessageListenerContainer-2] c.h.i.c.d.x.j.MyFixedBackOff [MyFixedBackOff.java:115] MyFixedBackOff currentAttempts = 0
2019-05-10 17:54:49,938 WARN [customMessageListenerContainer-2] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:871] Setup of JMS message listener invoker failed for destination 'queue:///CT_XSSL.CT_CPMX.MRZC_DGRM.0013' - trying to recover. Cause: JMSWMQ2008: Failed to open MQ queue 'CT_XSSL.CT_CPMX.MRZC_DGRM.0013'.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2085' ('MQRC_UNKNOWN_OBJECT_NAME').
2019-05-10 17:54:49,938 INFO [customMessageListenerContainer-2] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:921] Successfully refreshed JMS Connection
2019-05-10 17:54:49,953 INFO [customMessageListenerContainer-3] c.h.i.c.d.x.j.MyFixedBackOff [MyFixedBackOff.java:115] MyFixedBackOff currentAttempts = 0
2019-05-10 17:54:54,962 WARN [customMessageListenerContainer-3] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:871] Setup of JMS message listener invoker failed for destination 'queue:///CT_XSSL.CT_CPMX.MRZC_DGRM.0013' - trying to recover. Cause: JMSWMQ2008: Failed to open MQ queue 'CT_XSSL.CT_CPMX.MRZC_DGRM.0013'.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2085' ('MQRC_UNKNOWN_OBJECT_NAME').
2019-05-10 17:54:54,962 INFO [customMessageListenerContainer-3] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:921] Successfully refreshed JMS Connection
How can I make customMessageListenerContainer effectively a singleton ?
What makes you think it's not a singleton?
If you mean the thread names are incrementing (customMessageListenerContainer-2 etc), it's because by default a SimpleAsyncTaskExecutor is used and a new thread is used after each failure (and the previous one terminates).
You can change the executor to a different implementation (e.g. thread pool) if you want.
Singleton is the default scope.

Spring + tomee JTA transactions

I have been struggling through trying to build a very simple application that deploys to tomee using spring, hibernate and JMS. I believe that all of my configurations are correct (have the mysql xa data source and the xa active mq connection factory) but things aren't working as I would expect. Currently I have a simple service that writes using the injected entity manager then pushes to JMS within one method that is annotated as being transactional (spring annotation) but my message listener is being delivered these messages before the transaction is committed in spring.
I've tried using JMS template and the xa connection factory directly, but neither works properly. The template is configured with the jta transaction manager received from jndi. Any ideas what to look at for hints as to why the JMS sends are not participating in the same transaction as the database writes?
Spring Configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:encryption="http://www.jasypt.org/schema/encryption"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
http://www.jasypt.org/schema/encryption http://www.jasypt.org/schema/encryption/jasypt-spring31-encryption-1.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd"
default-autowire="byType" default-lazy-init="false">
<context:component-scan annotation-config="false" base-package="org.superbiz" />
<bean class="org.springframework.orm.jpa.DefaultJpaDialect" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
<property name="alwaysUseJndiLookup" value="false" />
<property name="jndiFactory" >
<ref local="jndiFactory"/>
</property>
</bean>
<bean id="jndiFactory" class="org.springframework.jndi.support.SimpleJndiBeanFactory">
<property name="resourceRef" value="true" />
</bean>
<bean id="PrintTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref local="jmsFactory" />
</property>
<property name="defaultDestinationName" value="resources/jms/PrintQueue" />
<property name="deliveryPersistent" value="true"/>
<!-- <property name="sessionTransacted" value="true"/> -->
<!-- <property name="sessionAcknowledgeMode" value="0"/> -->
</bean>
<bean id="PersistTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref local="jmsFactory" />
</property>
<property name="defaultDestinationName" value="resources/jms/PersistQueue" />
<property name="deliveryPersistent" value="true"/>
<!-- <property name="sessionTransacted" value="true"/> -->
<!-- <property name="sessionAcknowledgeMode" value="0"/> -->
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="defaultPersistenceUnitName" value="movie-unit" />
<property name="persistenceContexts">
<map>
<entry key="movie-unit" value="persistence/movie-unit" />
</map>
</property>
</bean>
<context:component-scan base-package="org.superbiz.ejb" annotation-config="false">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<jee:jndi-lookup id="jmsFactory" jndi-name="resources/jms/ConnectionFactory" expected-type="javax.jms.ConnectionFactory" />
<tx:jta-transaction-manager />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="printBean" class="org.superbiz.mdb.PrintBean"/>
<bean id="persistBean" class="org.superbiz.mdb.PersistBean"/>
<jms:listener-container container-type="default" connection-factory="jmsFactory" cache="none" transaction-manager="transactionManager" concurrency="1" receive-timeout="1000" prefetch="-1">
<jms:listener destination="resources/jms/PrintQueue" ref="printBean" />
<jms:listener destination="resources/jms/PersistQueue" ref="persistBean" />
</jms:listener-container>
</beans>
tomee.xml (cobbled together from http://tomee-openejb.979440.n4.nabble.com/MDB-doesn-t-read-messages-td4666169.html)
<Resource id="ActiveMQResourceAdapter" type="ActiveMQResourceAdapter">
BrokerXmlConfig=broker:(vm://localhost)
</Resource>
<Resource id="resources/jms/ConnectionFactory" type="javax.jms.ConnectionFactory">
ResourceAdapter = ActiveMQResourceAdapter
</Resource>
<Resource id="resources/jms/XAConnectionFactory" class-name="org.apache.activemq.ActiveMQXAConnectionFactory">
BrokerURL = vm://localhost
ResourceAdapter = ActiveMQResourceAdapter
</Resource>
<Resource id="resources/jms/PrintQueue" type="javax.jms.Queue"/>
<Resource id="resources/jms/PersistQueue" type="javax.jms.Queue"/>
<Resource id="MySQL Database" type="DataSource">
JdbcDriver com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
JdbcUrl jdbc:mysql://localhost/test
UserName test
</Resource>
I've tried several ways to include not using the XAConnectionFactory with the JMSTemplate configured to be sessionTransacted and not, removing the JMSTemplate and creating the connection/session/producer/message from the connectionFactory, but I've run into an issue each time. With manually creating the connection/session/producer/message from the ConnectionFactory I notice that the 20 items I attempt to write to the database then send to another JMS Queue start being read before the services transaction completes.
As far as I can tell everything is configured correctly (although I could definitely be wrong since this was pulled from lots of places). My goal is to be able to use the JMSTemplate instead of manually creating the connection/session/etc myself, but I'm at a loss for why this is happening at this point so any ideas are greatly appreciated.
I've also bumped the logging of the Spring JtaTransactionManager up and I see the following happening when the #Transactional method is called
DEBUG org.springframework.transaction.jta.JtaTransactionManager - Creating new transaction with name [org.superbiz.ejb.Movies.send]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
DEBUG org.springframework.transaction.jta.JtaTransactionManager - Initiating transaction commit
Then I see the my MDB code trying to retrieve the item from the entityManager (which works/fails intermittently). When it succeeds I see this
printing from MDB: director: director0title: title0year: 0
DEBUG org.springframework.transaction.jta.JtaTransactionManager - Initiating transaction commit
DEBUG org.springframework.transaction.jta.JtaTransactionManager - Creating new transaction with name [org.springframework.jms.listener.DefaultMessageListenerContainer#0]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
When it fails I see this
/***************** BROKEN ***************/
/*******************435265*****************/
/***************** BROKEN ***************/
DEBUG org.springframework.transaction.jta.JtaTransactionManager - Initiating transaction commit
DEBUG org.springframework.transaction.jta.JtaTransactionManager - Creating new transaction with name [org.springframework.jms.listener.DefaultMessageListenerContainer#0]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
I've further cranked up the logging
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] DEBUG org.springframework.transaction.jta.JtaTransactionManager - Creating new transaction with name [org.springframework.jms.listener.DefaultMessageListenerContainer#1]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
**bold** [org.springframework.jms.listener.DefaultMessageListenerContainer#0-1] DEBUG org.springframework.transaction.jta.JtaTransactionManager - Creating new transaction with name [org.springframework.jms.listener.DefaultMessageListenerContainer#0]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.support.TransactionSynchronizationManager - Initializing transaction synchronization
[org.springframework.jms.listener.DefaultMessageListenerContainer#0-1] TRACE org.springframework.transaction.support.TransactionSynchronizationManager - Initializing transaction synchronization
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.support.TransactionSynchronizationManager - Bound value [org.springframework.jms.connection.JmsResourceHolder#81032a4] for key [org.apache.activemq.ra.ActiveMQConnectionFactory#5ee0c65d] to thread [org.springframework.jms.listener.DefaultMessageListenerContainer#1-1]
[org.springframework.jms.listener.DefaultMessageListenerContainer#0-1] TRACE org.springframework.transaction.support.TransactionSynchronizationManager - Bound value [org.springframework.jms.connection.JmsResourceHolder#eaebd86] for key [org.apache.activemq.ra.ActiveMQConnectionFactory#5ee0c65d] to thread [org.springframework.jms.listener.DefaultMessageListenerContainer#0-1]
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] DEBUG org.springframework.transaction.jta.JtaTransactionManager - Participating in existing transaction
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.interceptor.TransactionInterceptor - Getting transaction for [org.superbiz.mdb.PersistBean.onMessage]
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.support.TransactionSynchronizationManager - Retrieved value [org.springframework.jms.connection.JmsResourceHolder#81032a4] for key [org.apache.activemq.ra.ActiveMQConnectionFactory#5ee0c65d] bound to thread [org.springframework.jms.listener.DefaultMessageListenerContainer#1-1]
Persisted finished, but not yet committed
Leaving persist, should commit
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.interceptor.TransactionInterceptor - Completing transaction for [org.superbiz.mdb.PersistBean.onMessage]
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.jta.JtaTransactionManager - Triggering beforeCommit synchronization
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.jta.JtaTransactionManager - Triggering beforeCompletion synchronization
[org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] TRACE org.springframework.transaction.support.TransactionSynchronizationManager - Removed value [org.springframework.jms.connection.JmsResourceHolder#81032a4] for key [org.apache.activemq.ra.ActiveMQConnectionFactory#5ee0c65d] from thread [org.springframework.jms.listener.DefaultMessageListenerContainer#1-1]
**bold** [org.springframework.jms.listener.DefaultMessageListenerContainer#1-1] DEBUG org.springframework.transaction.jta.JtaTransactionManager - Initiating transaction commit
Entering print
/***************** BROKEN ***************/
/*******************597852*****************/
/***************** BROKEN ***************/
in this case DefaultMessageListenerContainer#1-1 is my Persist bean and 0-1 is a bean that retrieves the entity by id and then prints the content.
I am not 100% sure how to read this, but it's interesting to me that the DMLC#1-1 commits well after a new transaction has begun on DMLC#0-1, but DMLC#0-1 sees the message. I would have thought that DMLC#0-1 would have needed to start a new transaction to see this OR since he received the JMS message the entity should also be persisted to the database.
Contents of my persist bean
#Override
#Transactional
public void onMessage(Message message) {
TextMessage msg = (TextMessage)message;
int x;
try {
x = Integer.parseInt(msg.getText());
Movie movie = new Movie("director" + x, "title" + x, x);
entityManager.persist(movie);
final long id = movie.getId();
template.send(new MessageCreator() {
#Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(Long.toString(id));
}
});
System.out.println("Persisted finished, but not yet committed");
System.out.println("Leaving persist, should commit");
} catch (Exception e) {
e.printStackTrace();
}
}
Contents of my print bean
public void onMessage(Message message) {
System.out.println("Entering print");
final TextMessage textMessage = (TextMessage) message;
try {
long id = Long.parseLong(textMessage.getText());
Movie movie = entityManager.find(Movie.class, id);
if(movie == null){
System.out.println("/***************** BROKEN ***************/");
System.out.println("/*******************" + id + "*****************/");
System.out.println("/***************** BROKEN ***************/");
} else {
System.out.println("updating: "+ movie);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The entire app is available at https://github.com/jej2003/simple-spring, running a vanilla Tomee 1.7.1 with the necessary hibernate jars added to the tomee/lib directory.
I'm really at a loss here, does no one run JTA transactions in Tomee with Spring?
After a ton of debugging it turns out that the failure was not in the JTA implementation, but more so my understanding of JTA in general. While JTA ensures that both transactions will successfully commit, it does not enforce an order apparently of those transactions. The answer was ultimately provided here https://jira.spring.io/browse/SPR-12535, by Stéphane Nicoll.

Spring taking long time to return cached instance of singleton bean - transactionManager

All API call are taking long time to respond because, spring is taking long time to return cached instance of singleton bean - transactionManager. Please see log, this behaviour is consistent for each request.
2
014-09-24 08:09:02,239 DEBUG servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing GET request for [/emsp/locations]
2014-09-24 08:09:02,239 DEBUG annotation.RequestMappingHandlerMapping - Looking up handler method for path /locations
2014-09-24 08:09:02,239 DEBUG annotation.RequestMappingHandlerMapping - Did not find handler method for [/locations]
2014-09-24 08:09:02,239 DEBUG servlet.DispatcherServlet - Last-Modified value for [/emsp/locations] is: -1
2014-09-24 08:09:02,240 DEBUG support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'integrationEvaluationContext'
2014-09-24 08:09:02,241 DEBUG support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'endpointLookupService'
2014-09-24 08:09:07,407 DEBUG support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'txManager'
2014-09-24 08:09:07,407 DEBUG hibernate4.HibernateTransactionManager - Creating new transaction with name [com.***.emsp.service.impl.EndpointLookupServiceImpl.getEndpointLocations]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2014-09-24 08:09:07,407 DEBUG hibernate4.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] orphanRemovals=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] collectionQueuedOps=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
2014-09-24 08:09:07,407 DEBUG hibernate4.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] orphanRemovals=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] collectionQueuedOps=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
2014-09-24 08:09:07,407 DEBUG internal.LogicalConnectionImpl - Obtaining JDBC connection
2014-09-24 08:09:07,407 DEBUG resourcepool.BasicResourcePool - trace com.mchange.v2.resourcepool.BasicResourcePool#7cfea9ab [managed: 1, unused: 0, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection#6a4d7764)
2014-09-24 08:09:07,407 DEBUG internal.LogicalConnectionImpl - Obtained JDBC connection
2014-09-24 08:09:07,407 DEBUG spi.AbstractTransactionImpl - begin
2014-09-24 08:09:07,408 DEBUG jdbc.JdbcTransaction - initial autocommit status: true
2014-09-24 08:09:07,408 DEBUG jdbc.JdbcTransaction - disabling autocommit
2014-09-24 08:09:07,408 DEBUG hibernate4.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mchange.v2.c3p0.impl.NewProxyConnection#3c0b2e6e]
2014-09-24 08:09:07,408 INFO impl.EndpointLookupServiceImpl - EndpointLookupServiceImpl::getEndpointLocations - called (Custom log - after this is almost instantaneous)
If you see these two lines specifically in the above line - there is a 5sec delay - this keeps increasing after a while but comes down once tomcat is restarted.
2014-09-24 08:09:02,241 DEBUG support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'endpointLookupService'
2014-09-24 08:09:07,407 DEBUG support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'txManager'
My spring config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.****.emsp" />
<!-- Transaction Manager Declaration -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/emsp" />
<property name="user" value="***" />
<property name="password" value="***" />
<!-- C3P0 properties -->
<property name="acquireIncrement" value="1" />
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="300" />
<property name="idleConnectionTestPeriod" value="3000" />
<!--property name="testConnectionOnCheckout" value="true" /> <property
name="preferredTestQuery" value="select 1;" / -->
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.****.emsp.entity" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
</beans>
And i'm using #Transactional annotation for my service APIs involving DB transaction.
Please suggest how to go about debugging this. Also let me know if any another info is required.
Request Handling code:
#Service
public class EndpointLookupServiceImpl implements EndpointLookupService {
private static final Logger logger = Logger
.getLogger(EndpointLookupServiceImpl.class);
#Autowired
EndpointLocationDaoImpl endpointLoctionDao;
#Autowired
SsidDaoImpl ssidDao;
#Override
#Transactional
public EndpointLocationsResp getEndpointLocations(
String xJwtAssertionHeader, Map<String, List<String>> reqParams) {
logger.info("EndpointLookupServiceImpl::getEndpointLocations - called with xJwtAssertionHeader:"
+ xJwtAssertionHeader + " reqParams:" + reqParams);
.....
}
}
Using spring integration as controller for invoking the service:
<int-http:inbound-gateway id="endpointLocById"
request-channel="endpointLocByIdIn"
supported-methods="GET"
path="/locations/{locationId}"
mapped-request-headers="*"
payload-expression="#pathVariables.locationId" >
</int-http:inbound-gateway>
<int:channel id="endpointLocByIdIn"/>
<int:service-activator input-channel="endpointLocByIdIn" expression="#endpointLookupService.getEndpointLocationByLocationId(headers['x-jwt-assertion'], payload)" output-channel="out" />
Take thread dumps just before and after you see the blocking to see what your main thread is doing, Spring loads beans in a single thread, so you should be able to see where it is stuck and debug that even more.

JTA EntityManager cannot use getTransaction() [Spring + Hibernate + EntityManager]

I am using Spring + JPA + Hibernate + EntityManager to talk to the database. I am getting 'A JTA EntityManager cannot use getTransaction()' error. Please provide your insights and help me resolve the issue.
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
... xmlns definitions...
xsi:schemaLocation="...">
<context:component-scan base-package="com.mycompany.myproject" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="myDAO" class="com.mycompany.myproject.dao.myDAO" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence ... xmlns definitions xsi:schemaLocation="..." version="1.0">
<persistence-unit name="TEST_DS">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/TEST_DS</jta-data-source>
<class>com.twinspires.exchange.model.Test</class>
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" /> <!-- create-drop update -->
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
</properties>
</persistence-unit>
</persistence>
Exception Stack Trace (Excerpt)
15:47:43,340 INFO [STDOUT] DEBUG: org.springframework.transaction.annotation.AnnotationTransactionAttributeSource - Adding transactional method 'getName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
15:47:43,343 INFO [STDOUT] DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
15:47:43,356 INFO [STDOUT] DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Creating new transaction with name [com.twinspires.exchange.dao.PicDAO.getName]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
15:47:44,114 INFO [STDOUT] DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl#c629e5] for JPA transaction
15:47:44,124 INFO [STDOUT] DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Could not rollback EntityManager after failed transaction begin
15:47:44,125 INFO [STDOUT] java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
15:47:44,125 INFO [STDOUT] at org.hibernate.ejb.AbstractEntityManagerImpl.getTransaction(AbstractEntityManagerImpl.java:818)
15:47:44,126 INFO [STDOUT] at org.springframework.orm.jpa.JpaTransactionManager.closeEntityManagerAfterFailedBegin(JpaTransactionManager.java:412)
15:47:44,127 INFO [STDOUT] at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:381)
15:47:44,128 INFO [STDOUT] at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
15:47:44,129 INFO [STDOUT] at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
15:47:44,129 INFO [STDOUT] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
15:47:44,130 INFO [STDOUT] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
15:47:44,131 INFO [STDOUT] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
15:47:44,131 INFO [STDOUT] at $Proxy175.getName(Unknown Source)
Folowing is my dao class:-
public class MyDao implements IMyDao {
#PersistenceContext(unitName = "TEST_DS")
private EntityManager entityManager;
#Transactional
public String getName() {
final Query query = entityManager.createQuery("from TestTable");
final Object obj = query.getResultList().get(0);
return obj == null ? "Empty" : (String) obj;
}
}
Your help highly appreciated.
Remove the jta-datasource from persitence.xml, configure datasource as a bean j2ee:jdni-lookup and inject it into the LocalContainerEntityManagerFactoryBean
Remove this from persistence.xml
<jta-data-source>java:/TEST_DS</jta-data-source>
Configure the transaction-type to resource local
<persistence-unit name="TEST_DS" transaction-type="RESOURCE_LOCAL">
Change to your beans.xml
<j2ee:jndi-lookup id="dataSource" jndi-name="java:/TEST_DS"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
First of all I want to tell you I had the same problem. Researching about that I found this page with your post and the answer by "gkamal".
I think that the answer comes to say that if you are trying to use "global" JTA transaction in your application and it doesn't work then don't use it, use in its place a "local" JDBC transaction.
But if you need to use global JTA transaction then you must use it.
Well I am going to give you the solution I found in my resarch.
There are properties that are application server dependent. I use glassfish and this solution works fine, but I think you are using JBOSS (due to the value you are using in the jta-data-source in your persistence.xml) I will write the values for a JBOSS AS, but in JBOSS AS I don't prove it, I just prove it only in glassfish.
In your persistence.xml you have to put another property:
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
The value of this property is AP server dependent.
In your beans.xml file you have to take a look in the entity manager factory and transaction manager. Morover you have indicate in your web.xml which persistence units you are referencing in your application.
beans.xml
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="TEST_DS"/>
</bean>
In your transaction manager you are using entity manager factory but you don't have to do that. You have to indicate the transaction manager and user transaction used by your app server, this way
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="java:appserver/TransactionManager"/>
<property name="userTransactionName" value="java:comp/UserTransaction"/>
</bean>
The values of those properties are app server dependent (I use glassfish). I think you have to use the values for jboss ap:
<property name="transactionManagerName" value="java:/TransactionManager"/>
<property name="userTransactionName" value="UserTransaction"/>
But I didn't prove it.
Last, in glassfish I have to put in beans.xml (and I don't know why) the following bean (I think in jboss ap it isn't necessary but you might prove it)
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" >
<property name="persistenceUnits">
<map>
<entry key="TEST_DS" value="persistence/TEST_DS"/>
</map>
</property>
</bean>
In your web.xml you need reference the persistence units your application will use.
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/TEST_DS</persistence-unit-ref-name>
<persistence-unit-name>TEST_DS</persistence-unit-name>
</persistence-unit-ref>
I hope that the solution is of help for you. It works for me.

Resources