Why am I getting a 1 minute delay when creating a transaction in spring/hibernate/weblogic - spring

I'm getting a minute delay when calling a transactional bean, this does not occur always.
Sorry for the code and logs, they are a bit redacted, mostly to hide company names and business stuff.
The call to this.generalService.consultarDeuda takes a minute until the first line inside of it is logged.
#Override
public Response getConsultarDeuda(String requerimiento, String ip, String terminal, String canal,
ConsultarDeudaReqDTO request) throws CompanyRESTServiceException {
try {
LOGGER.info(" // first log inside my rest service ");
final ConsultaDeudaRespDTO response = this.generalService.consultarDeuda(new Date(), requerimiento, ip,
terminal, canal, request); // <-- this call takes a minute
LOGGER.info("generalService.consultarDeuda FIN requerimiento: " + requerimiento + " " + response + "\n");
return Response.ok(response).build();
} catch (ClientException e) {
LOGGER.info("error description");
return Response.status(Status.BAD_REQUEST) .entity(new ErrorResponse(e.getCodigo(), e.getMessage(), e.getMensajeInterno())).build();
} catch (Throwable t) {
LOGGER.error("Error en generalService.consultarDeuda: " + t.getMessage(), t);
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorResponse(ResponseEnum.ERROR_GENERICO.getCodigo(), t.getMessage(), null)).build();
}
}
Lines 4 and 5 show the minute gap, this seems to occur randomly.
2022-11-11 14:46:22,410 DEBUG impl.GeneralRESTServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralRESTServiceImpl.java:70) - // first log inside my rest service
2022-11-11 14:46:22,410 DEBUG support.AbstractPlatformTransactionManager [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (AbstractPlatformTransactionManager.java:367) - Creating new transaction with name [company.app.service.impl.GeneralServiceImpl.consultarDeuda]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-java.lang.RuntimeException,-company.app.service.exception.SomeException,-company.framework.persistence.dao.exception.CompanyPersistenceException
2022-11-11 14:46:22,410 DEBUG hibernate5.HibernateTransactionManager [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (HibernateTransactionManager.java:435) - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
2022-11-11 14:46:22,410 DEBUG hibernate5.HibernateTransactionManager [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (HibernateTransactionManager.java:445) - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
2022-11-11 14:47:22,517 DEBUG hibernate5.HibernateTransactionManager [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (HibernateTransactionManager.java:513) - Exposing Hibernate transaction as JDBC transaction [weblogic.jdbc.wrapper.PoolConnection_oracle_jdbc_driver_T4CConnection#c583]
2022-11-11 14:47:22,517 DEBUG impl.GeneralServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralServiceImpl.java:68) - // First log inside my transactional bean
2022-11-11 14:47:22,517 DEBUG impl.GeneralServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralServiceImpl.java:74) - // Redacted but not relevant
2022-11-11 14:47:22,518 DEBUG impl.GeneralServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralServiceImpl.java:81) - // Redacted but not relevant
2022-11-11 14:47:22,521 DEBUG impl.GeneralServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralServiceImpl.java:101) - // Redacted but not relevant
2022-11-11 14:47:22,522 DEBUG impl.GeneralServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralServiceImpl.java:109) - // Redacted but not relevant
2022-11-11 14:47:22,523 DEBUG impl.GeneralServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralServiceImpl.java:125) - // Redacted but not relevant
2022-11-11 14:47:22,523 DEBUG impl.ClientRestClientImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (ClientRestClientImpl.java:33) - // Redacted but not relevant
2022-11-11 14:47:22,523 DEBUG impl.ClientRestClientImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (ClientRestClientImpl.java:43) - // Redacted but not relevant
2022-11-11 14:47:22,834 DEBUG impl.ClientRestClientImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (ClientRestClientImpl.java:47) - // Redacted but not relevant
2022-11-11 14:47:22,835 DEBUG impl.ClientRestClientImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (ClientRestClientImpl.java:73) - // Redacted but not relevant
2022-11-11 14:47:24,611 DEBUG impl.ClientRestClientImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (ClientRestClientImpl.java:78) - // Redacted but not relevant
2022-11-11 14:47:24,611 INFO impl.CompanyGenericDAOImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (CompanyGenericDAOImpl.java:196) - Escribiendo entidad...
2022-11-11 14:47:24,616 ERROR impl.GeneralServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralServiceImpl.java:160) - // some business data, this is logged as error but should be info
2022-11-11 14:47:24,616 DEBUG support.AbstractPlatformTransactionManager [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (AbstractPlatformTransactionManager.java:851) - Initiating transaction rollback
2022-11-11 14:47:24,617 DEBUG hibernate5.HibernateTransactionManager [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (HibernateTransactionManager.java:597) - Rolling back Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[company.app.entity.EstadoRegistro#0], EntityKey[company.app.entity.Transaccion#6864], EntityKey[company.app.entity.Canal#1], EntityKey[company.app.entity.Terminal#1], EntityKey[company.app.entity.Impuesto#2]],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
2022-11-11 14:47:24,618 DEBUG hibernate5.HibernateTransactionManager [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (HibernateTransactionManager.java:666) - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[company.app.entity.EstadoRegistro#0], EntityKey[company.app.entity.Transaccion#6864], EntityKey[company.app.entity.Canal#1], EntityKey[company.app.entity.Terminal#1], EntityKey[company.app.entity.Impuesto#2]],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction
2022-11-11 14:47:24,619 DEBUG impl.GeneralRESTServiceImpl [[ACTIVE] ExecuteThread: '14' for queue: 'weblogic.kernel.Default (self-tuning)'] (GeneralRESTServiceImpl.java:82) - Error (managed error) en generalService.consultarDeuda SomeException and then more business specific data
Aspect configuration
<aop:config proxy-target-class="false">
<aop:pointcut id="client.tx.pointcut"
expression="execution(* company.framework.services.CompanyService+.*(..))" />
<aop:advisor advice-ref="client.tx.advice"
pointcut-ref="client.tx.pointcut" />
</aop:config>
<tx:advice id="clientservices.tx.advice" transaction-manager="clientservices.transaction.manager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="*"
rollback-for="java.lang.RuntimeException, company.app.service.exception.ClientException, company.framework.persistence.dao.exception.CompanyPersistenceException" />
</tx:attributes>
</tx:advice>
Any ideas what could be happening?
Is there some logging I can add to have a more detailed picture of what is happening?
Thank you!

Related

Why Weblogic server is not able to access Oracle DB account on localhost?

I have an Spring MVC application with oracle db for storage. I have deployed SpringMVC.war in tomcat and its working fine. But whenever I am deploying my application on Weblogic, it is throwing following exception
I have an account with the name "Asif123" on Oracle DB and is configured in "application-context.xml" in my project, but it is only accessible in Tomcat , not Weblogic.
application-context.xml
<bean id="ds" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/comp/env/ds1"/>
</bean>
Successful datasource test:
####<30-Oct-2017, 3:27:00,931 PM IST> <Error> <Deployer> <asif-dell> <AdminServer> <[STANDBY] ExecuteThread: '11' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <727e01e2-9cca-411b-8bc9-290fc833664e-00000014> <1509357420931> <[severity-value: 8] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-149265> <Failure occurred in the execution of deployment request with ID "155312441642365" for task "weblogic.deploy.configChangeTask.1" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: java.sql.SQLException: Access denied for user 'asif123'#'localhost' (using password: YES)"
weblogic.application.ModuleException: java.sql.SQLException: Access denied for user 'asif123'#'localhost' (using password: YES)
at weblogic.jdbc.module.JDBCModule.prepare(JDBCModule.java:411)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:192)
at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:187)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.flow.ModuleStateDriver.prepare(ModuleStateDriver.java:37)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:77)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:55)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:727)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:239)
at weblogic.application.internal.SingleModuleDeployment.prepare(SingleModuleDeployment.java:52)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:158)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:65)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:229)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:103)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:241)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:794)
at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1340)
at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:235)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:177)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:186)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.prepare(DeploymentReceiverCallbackDeliverer.java:42)
at weblogic.deploy.service.internal.statemachines.targetserver.AwaitingContextUpdateCompletion.callDeploymentReceivers(AwaitingContextUpdateCompletion.java:170)
at weblogic.deploy.service.internal.statemachines.targetserver.AwaitingContextUpdateCompletion.handleContextUpdateSuccess(AwaitingContextUpdateCompletion.java:66)
at weblogic.deploy.service.internal.statemachines.targetserver.AwaitingContextUpdateCompletion.contextUpdated(AwaitingContextUpdateCompletion.java:32)
at weblogic.deploy.service.internal.targetserver.TargetDeploymentService.notifyContextUpdated(TargetDeploymentService.java:232)
at weblogic.deploy.service.internal.DeploymentService$1.run(DeploymentService.java:210)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
Caused By: java.sql.SQLException: Access denied for user 'asif123'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1058)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2396)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2429)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2214)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:797)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:31)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
The fact that you are getting a MySQL error message when connecting to an Oracle database might be a bit of a clue.
Check your Weblogic datasource type - have you incorrectly configured it to be a MySQL connection to an Oracle DB ?

Spring MVC does not see resources folder

Spring does not see resources folder even after adding <mvc:resources mapping="/resources/**" location="/resources"/>
I am typing localhost:8080/resources/qwerty.txt (file is created) and Dispatcher servlet is solving it by ViewResolver like "/WEB-INF/views/resources/qwerty.jsp"
Also I have found a similar project on github with "resorces" folder in "webapp" and there everything is OK. After making the same procedure like I descriped above - spring displays qwerty.txt on the screen.
This is Tomcat console:
Request #1:
TRACE 2017-04-27 15:32:23,455 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:23,456 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'di' processing GET request for [/resources/qwerty.txt]
TRACE 2017-04-27 15:32:23,460 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#444835f1] in DispatcherServlet with name 'di'
DEBUG 2017-04-27 15:32:23,463 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /resources/qwerty.txt
TRACE 2017-04-27 15:32:23,473 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/resources/qwerty.txt] : [{[],methods=[GET]}]
DEBUG 2017-04-27 15:32:23,473 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public void web.SimpleController.index()]
DEBUG 2017-04-27 15:32:23,474 [http-bio-8080-exec-1] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'simpleController'
TRACE 2017-04-27 15:32:23,475 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter#75ad2983]
TRACE 2017-04-27 15:32:23,475 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter#1d7ba137]
TRACE 2017-04-27 15:32:23,476 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#2efb2c32]
DEBUG 2017-04-27 15:32:23,476 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/resources/qwerty.txt] is: -1
TRACE 2017-04-27 15:32:23,500 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Invoking [SimpleController.index] method with arguments []
TRACE 2017-04-27 15:32:23,500 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Method [index] returned [null]
DEBUG 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'resources/qwerty'
TRACE 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.web.servlet.view.InternalResourceViewResolver - Cached view [resources/qwerty]
DEBUG 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'resources/qwerty'; URL [/WEB-INF/views/resources/qwerty.jsp]] in DispatcherServlet with name 'di'
TRACE 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.web.servlet.view.JstlView - Rendering view with name 'resources/qwerty' with model {} and static attributes {}
DEBUG 2017-04-27 15:32:23,521 [http-bio-8080-exec-1] org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/resources/qwerty.jsp] in InternalResourceView 'resources/qwerty'
TRACE 2017-04-27 15:32:23,527 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:23,527 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Successfully completed request
TRACE 2017-04-27 15:32:23,529 [http-bio-8080-exec-1] org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in WebApplicationContext for namespace 'di-servlet': ServletRequestHandledEvent: url=[/resources/qwerty.txt]; client=[127.0.0.1]; method=[GET]; servlet=[di]; session=[null]; user=[null]; time=[89ms]; status=[OK]
Request #2:
TRACE 2017-04-27 15:32:49,272 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:49,273 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'di' processing GET request for [/resources/qwerty.txt]
TRACE 2017-04-27 15:32:49,274 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#444835f1] in DispatcherServlet with name 'di'
DEBUG 2017-04-27 15:32:49,274 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /resources/qwerty.txt
TRACE 2017-04-27 15:32:49,275 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/resources/qwerty.txt] : [{[],methods=[GET]}]
DEBUG 2017-04-27 15:32:49,275 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public void web.SimpleController.index()]
DEBUG 2017-04-27 15:32:49,275 [http-bio-8080-exec-3] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'simpleController'
TRACE 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter#75ad2983]
TRACE 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter#1d7ba137]
TRACE 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#2efb2c32]
DEBUG 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/resources/qwerty.txt] is: -1
TRACE 2017-04-27 15:32:49,277 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Invoking [SimpleController.index] method with arguments []
TRACE 2017-04-27 15:32:49,284 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Method [index] returned [null]
DEBUG 2017-04-27 15:32:49,287 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'resources/qwerty'; URL [/WEB-INF/views/resources/qwerty.jsp]] in DispatcherServlet with name 'di'
TRACE 2017-04-27 15:32:49,287 [http-bio-8080-exec-3] org.springframework.web.servlet.view.JstlView - Rendering view with name 'resources/qwerty' with model {} and static attributes {}
DEBUG 2017-04-27 15:32:49,288 [http-bio-8080-exec-3] org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/resources/qwerty.jsp] in InternalResourceView 'resources/qwerty'
TRACE 2017-04-27 15:32:49,289 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:49,289 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Successfully completed request
TRACE 2017-04-27 15:32:49,289 [http-bio-8080-exec-3] org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in WebApplicationContext for namespace 'di-servlet': ServletRequestHandledEvent: url=[/resources/qwerty.txt]; client=[127.0.0.1]; method=[GET]; servlet=[di]; session=[null]; user=[null]; time=[18ms]; status=[OK]
servlet context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="controller, model, service, todo, web"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/"
p:suffix=".jsp"
/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:annotation-driven />
What I am doing wrong?
SOLVED:
I just changed mapping for some methods from default to their real names and everything gone
Magic
Does anyone knows why it is working in such strange way?

Data is not written into the XML file from mongodb using Spring Batch, Why?

I am developing Spring Batch MongoDB to XML example. I was successfully developed the application, but I dont see data is getting written into the XML file. Could you please guide me what is the issue ? I dont see any working example yet on the web.
job-report.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd">
<!-- Actual Job -->
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="mongodbItemReader" writer="xmlItemWriter" commit-interval="1">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="com.mkyong.model.Report" />
<property name="query" value="{'_id':{$gt:0} }" />
<property name="sort">
<util:map>
<entry key="id" value="#{T(org.springframework.data.domain.Sort.Direction).ASC}" />
</util:map>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="classpath:xml/report.xml" />
<property name="marshaller" ref="reportUnMarshaller" />
<property name="rootTagName" value="record" />
</bean>
<bean id="reportUnMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>com.mkyong.model.Report</value>
</property>
</bean>
</beans>
App.java
public class App {
public static void main(String[] args) {
String[] springConfig = { "database.xml", "context.xml", "job-report.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("reportJob");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
Logs from console:
14:58:52.487 [main] DEBUG o.s.b.c.s.c.StepContextRepeatCallback - Preparing chunk execution for StepContext: org.springframework.batch.core.scope.context.StepContext#aa594b
14:58:52.487 [main] DEBUG o.s.b.c.s.c.StepContextRepeatCallback - Chunk execution starting: queue size=0
14:58:52.487 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.487 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Starting repeat context.
14:58:52.487 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat operation about to start at count=1
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - find using query: { "_id" : { "$gt" : 0}} fields: null for class: class com.mkyong.model.Report in collection: report
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[yourdb]
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Registering Spring transaction synchronization for MongoDB instance yourdb.
14:58:52.488 [main] DEBUG org.mongodb.driver.protocol.query - Sending query of namespace yourdb.report on connection [connectionId{localValue:3, serverValue:53}] to server 127.0.0.1:27017
14:58:52.489 [main] DEBUG org.mongodb.driver.protocol.query - Query completed
14:58:52.489 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat is complete according to policy and result value.
14:58:52.489 [main] DEBUG o.s.b.c.s.item.ChunkOrientedTasklet - Inputs not busy, ended: true
14:58:52.489 [main] DEBUG o.s.b.core.step.tasklet.TaskletStep - Applying contribution: [StepContribution: read=0, written=0, filtered=0, readSkips=0, writeSkips=0, processSkips=0, exitStatus=EXECUTING]
14:58:52.489 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Participating in existing transaction
14:58:52.490 [main] DEBUG o.s.b.core.step.tasklet.TaskletStep - Saving step execution before commit: StepExecution: id=1, version=5, name=step1, status=STARTED, exitStatus=EXECUTING, readCount=4, filterCount=0, writeCount=4 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=5, rollbackCount=0, exitDescription=
14:58:52.490 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Participating in existing transaction
14:58:52.491 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.491 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#a8ee09]
14:58:52.492 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat is complete according to policy and result value.
14:58:52.492 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution success: id=1
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#5b3037]
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.494 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.494 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#baa89c]
14:58:52.495 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution complete: StepExecution: id=1, version=7, name=step1, status=COMPLETED, exitStatus=COMPLETED, readCount=4, filterCount=0, writeCount=4 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=5, rollbackCount=0
14:58:52.495 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.496 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.496 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#1f2ebae]
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.step1 with status=COMPLETED
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Handling state=reportJob.end1
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.end1 with status=COMPLETED
14:58:52.497 [main] DEBUG o.s.batch.core.job.AbstractJob - Job execution complete: JobExecution: id=0, version=1, startTime=Tue Jan 10 14:58:52 IST 2017, endTime=null, lastUpdated=Tue Jan 10 14:58:52 IST 2017, status=COMPLETED, exitStatus=exitCode=COMPLETED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[reportJob]], jobParameters=[{}]
14:58:52.497 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.501 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.501 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#498b0]
14:58:52.501 [main] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [FlowJob: [name=reportJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Exit Status : COMPLETED
Done
In this example, I do need to manually create xml/report.xml into the classpath. Ideally it should be automatic. Right?
I got the solution to this problem from the link: Complex XML using Spring Batch; StaxEventItemWriter ; Jaxb2Marshaller. Also I should use
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:outputs/report.xml" />
<property name="encoding" value="ISO-8859-1" />
<property name="version" value="1.0" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="record" />
</bean>

Sharing transaction with AbstractRoutingDataSource

I've a problem very close to this one Sharing a transaction while using AbstractRoutingDataSource to switch datasources but I'm not able to solve using the accepted answer. I've a transactional method who have to write the same entity into two different datasource in transactional mode. When transaction commit I've a
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (VETO_PROD.SYS_C0013988) violated
This is my Transalctional method:
#Override
#Transactional(propagation = Propagation.REQUIRES_NEW)
public ContactTypeJson definisciNuovaContactType(String descrizione) throws Exception {
String functionCode = RandomStringUtils.randomAlphanumeric(5).toUpperCase();
LOGGER.debug("Ho generato la functionCode[" + functionCode + "]");
while (!isContactTypeAvailable(functionCode) || !notificatorService.isFunctionCodeAvailable(functionCode)) {
LOGGER.debug("La functionCode[" + functionCode + "] e' gia' in utilizzo, genero una nuova...");
functionCode = RandomStringUtils.randomAlphanumeric(5).toUpperCase();
LOGGER.debug("...la nuova functionCode generata e' [" + functionCode + "]");
}
ContactType contactType = new ContactType();
contactType.setName(functionCode);
contactType.setDescription(descrizione);
notificatorService.insertNewFunction(functionCode, descrizione);
entityManagerFRVP0.flush();
entityManagerFRVP0.clear();
VetrinaContextHolder.setTargetDataSource(VetrinaToolConstants.FRVP_DATASOURCE);
entityManagerFRVP0.persist(contactType);
entityManagerFRVP0.flush();
entityManagerFRVP0.clear();
VetrinaContextHolder.setTargetDataSource(VetrinaToolConstants.PWVP_DATASOURCE);
ContactType contactType1 = new ContactType();
contactType1.setName(functionCode);
contactType1.setDescription(descrizione);
entityManagerFRVP0.persist(contactType1);
VetrinaContextHolder.clearTargetDataSource();
ContactTypeToJsonConverter converter = new ContactTypeToJsonConverter();
return converter.convert(contactType);
}
This is the JPA log:
2013-07-15 10:47:59,570 DEBUG [sql] 2013-07-15 10:47:59.569--ServerSession(26361419)--Connection(16434777)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT VET_SEQ_CONTACT_TYPE.NEXTVAL FROM DUAL
2013-07-15 10:47:59,581 DEBUG [sql] 2013-07-15 10:47:59.58--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (81, Prova doppione, 16XOV, NULL)
2013-07-15 10:47:59,596 DEBUG [sql] 2013-07-15 10:47:59.595--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT VET_SEQ_CONTACT_TYPE.NEXTVAL FROM DUAL
2013-07-15 10:47:59,601 DEBUG [sql] 2013-07-15 10:47:59.6--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (82, Prova doppione, 16XOV, NULL)
This the stack:
2013-07-15 10:47:59,421 DEBUG [WebLogicJtaTransactionManager] Creating new transaction with name [com.intesasanpaolo.frvp0.alten.vetrinatool.service.console.ConsoleServiceImpl.definisciNuovaContactType]: PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT; ''
2013-07-15 10:47:59,430 DEBUG [EntityManagerFactoryUtils] Opening JPA EntityManager
2013-07-15 10:47:59,430 DEBUG [EntityManagerFactoryUtils] Registering transaction synchronization for JPA EntityManager
2013-07-15 10:47:59,483 DEBUG [TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource] Adding transactional method 'findOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
2013-07-15 10:47:59,483 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,483 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,483 DEBUG [EntityManagerFactoryUtils] Opening JPA EntityManager
2013-07-15 10:47:59,483 DEBUG [EntityManagerFactoryUtils] Registering transaction synchronization for JPA EntityManager
2013-07-15 10:47:59,542 DEBUG [AnnotationTransactionAttributeSource] Adding transactional method 'insertNewFunction' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-07-15 10:47:59,543 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,543 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,543 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,543 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,549 DEBUG [TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource] Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-07-15 10:47:59,549 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,550 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,600 DEBUG [EntityManagerFactoryUtils] Closing JPA EntityManager
2013-07-15 10:47:59,600 DEBUG [EntityManagerFactoryUtils] Closing JPA EntityManager
2013-07-15 10:47:59,600 DEBUG [WebLogicJtaTransactionManager] Initiating transaction commit
2013-07-15 10:47:59,827 DEBUG [DispatcherServlet] Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'jsonView'; model is {hasErrors=true, errorCode=GEN_EX, errorMessages=Errore generico}
org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is weblogic.transaction.RollbackException: Unexpected exception in beforeCompletion: sync=org.eclipse.persistence.transaction.JTASynchronizationListener#2f0af4
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (VETO_PROD.SYS_C0013988) violated
Error Code: 1
Call: INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (82, 'Prova doppione', '16XOV', NULL)
Query: InsertObjectQuery(ContactType [id=82, name=16XOV, description=Prova doppione, fasiAssociate={[]}, faseDiDefault=null])
at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1014)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:387)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy310.definisciNuovaContactType(Unknown Source)
at com.intesasanpaolo.frvp0.alten.vetrinatool.mvc.console.controller.CreaContactTypeController.creaNuovaContactType(CreaContactTypeController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
I'm using WebLogic 10.3.5 with XA datasources and org.springframework.transaction.jta.WebLogicJtaTransactionManager
Any idea?
You are violating a unique constraint. I assume you have one defined on the Contact name, so you cannot insert two contacts with the same name.
Trying to switch the connection under a DataSource on the fly seems like a very, very, bad idea. Instead you should have two persistence units, one going to one database, and one going to the other.
You may also want to investigate EclipseLink's data partitioning, or composite persistence units.
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Partitioning
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Composite

transaction cannot complete using JtaTransactionManager, while using JpaTransactionManager works fine

I have a big problem with using JTA and Spring Data (1.9.2). My project works fine when I'm using JpaTransactionManager. I have also tried JdbcTemplate (no Spring Data) with JTA, that also works fine. I have tried OpenJPA (2.2.1) and Hibernate (4.2.8), both Jetty and Websphere Liberty server. They all fails using JTA and works fine using JPA Transaction Manager. The datasource is XA capable, and currently Derby Embedded. Springframework is v4.2.1
This is my Entity
#Entity
#Table(name = "SAKSSTATUS")
public class SaksStatus implements Serializable {
#Id
#Column(name = "ID")
private String id;
public SaksStatus() {};
public SaksStatus(String id) {
this.id = id;
}
}
My DAO
public interface SaksStatusDao extends JpaRepository<SaksStatus, String> {
}
My transaction
#Transactional
public void test() {
logger.info("deleting before testing ");
saksStatusDao.deleteAll();
logger.info("save...");
saksStatusDao.save(new SaksStatus("100"));
logger.info("save OK");
logger.info("result: {}", saksStatusDao.findAll());
logger.info("removing ...");
saksStatusDao.deleteAll();
logger.info("flush ...");
saksStatusDao.flush();
}
My application context :
<context:annotation-config/>
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/derbyEmbedded" />
<context:component-scan base-package="no.klp.saksstatus.dao" />
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:jta-transaction-manager />
<jpa:repositories base-package="no.klp.saksstatus.dao"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="no.klp.saksstatus.dao.entities" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"></bean>
<bean class="no.klp.saksstatus.services.SaksStatusService"/>
My persistence file
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="persistenceunit" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>no.klp.saksstatus.dao.entities.SaksStatus</class>
</persistence-unit>
</persistence>
My enhancer plugin in pom.xml
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.3.0</version>
<configuration>
<includes>no/klp/saksstatus/dao/entities/**/*.class</includes>
<addDefaultConstructor>true</addDefaultConstructor>
<enforcePropertyRestrictions>true</enforcePropertyRestrictions>
<persistenceXmlFile>${basedir}/META-INF/persistence.xml</persistenceXmlFile>
</configuration>
<executions>
<execution>
<id>enhancer</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
</plugin>
So when executing my transaction I've got his log :
2016-02-02 13:34:52,391 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:367 - Creating new transaction with name [no.klp.saksstatus.services.SaksStatusService.test]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2016-02-02 13:34:52,423 saksstatus-service INFO no.klp.saksstatus.services.SaksStatusService:30 - deleting before testing
2016-02-02 13:34:52,429 saksstatus-service DEBUG org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:351 - Adding transactional method 'deleteAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2016-02-02 13:34:52,429 saksstatus-service DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory:250 - Returning cached instance of singleton bean 'transactionManager'
2016-02-02 13:34:52,430 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:476 - Participating in existing transaction
2016-02-02 13:34:52,456 saksstatus-service DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils:272 - Opening JPA EntityManager
2016-02-02 13:34:52,457 saksstatus-service DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils:290 - Registering transaction synchronization for JPA EntityManager
[err] 1409 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 26992656> executing prepstmnt 1533150303 SELECT t0.ID FROM SAKSSTATUS t0
[err] 1410 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 26992656> [0 ms] spent
2016-02-02 13:34:52,674 saksstatus-service INFO no.klp.saksstatus.services.SaksStatusService:32 - save...
2016-02-02 13:34:52,675 saksstatus-service DEBUG org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:351 - Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2016-02-02 13:34:52,675 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:476 - Participating in existing transaction
[err] 1525 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 1984659730> executing prepstmnt 715039869 SELECT t0.ID FROM SAKSSTATUS t0 WHERE t0.ID = ? [params=?]
[err] 1526 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 1984659730> [0 ms] spent
2016-02-02 13:34:52,778 saksstatus-service INFO no.klp.saksstatus.services.SaksStatusService:34 - save OK
2016-02-02 13:34:52,779 saksstatus-service DEBUG org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:351 - Adding transactional method 'findAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
2016-02-02 13:34:52,779 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:476 - Participating in existing transaction
[err] 1539 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 977455988> executing prepstmnt 1441490501 SELECT t0.ID FROM SAKSSTATUS t0
[err] 1539 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 977455988> [0 ms] spent
2016-02-02 13:34:52,781 saksstatus-service INFO no.klp.saksstatus.services.SaksStatusService:35 - result: []
2016-02-02 13:34:52,781 saksstatus-service INFO no.klp.saksstatus.services.SaksStatusService:36 - removing ...
2016-02-02 13:34:52,781 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:476 - Participating in existing transaction
[err] 1541 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 1721406628> executing prepstmnt 174725407 SELECT t0.ID FROM SAKSSTATUS t0
[err] 1541 default TRACE [Default Executor-thread-2] openjpa.jdbc.SQL - <t 925948525, conn 1721406628> [0 ms] spent
2016-02-02 13:34:52,783 saksstatus-service INFO no.klp.saksstatus.services.SaksStatusService:38 - flush ...
2016-02-02 13:34:52,783 saksstatus-service DEBUG org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:351 - Adding transactional method 'flush' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2016-02-02 13:34:52,784 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:476 - Participating in existing transaction
2016-02-02 13:34:52,785 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:858 - Participating transaction failed - marking existing transaction as rollback-only
2016-02-02 13:34:52,785 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:1072 - Setting JTA transaction rollback-only
2016-02-02 13:34:52,786 saksstatus-service DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory:250 - Returning cached instance of singleton bean 'entityManagerFactory'
2016-02-02 13:34:52,790 saksstatus-service DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils:435 - Closing JPA EntityManager
2016-02-02 13:34:52,802 saksstatus-service DEBUG org.springframework.transaction.jta.JtaTransactionManager:851 - Initiating transaction rollback
[ERROR ] SRVE0777E: Exception thrown by application class 'org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible:413'
org.springframework.dao.InvalidDataAccessApiUsageException: Can only perform operation while a transaction is active.; nested exception is <openjpa-2.2.1-r422266:1396819 nonfatal user error> org.apache.openjpa.persistence.TransactionRequiredException: Can only perform operation while a transaction is active.
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:413)
at org.springframework.orm.jpa.DefaultJpaDialect.translateExceptionIfPossible(DefaultJpaDialect.java:122)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131)
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:207)
at com.sun.proxy.$Proxy41.flush(Unknown Source)
at no.klp.saksstatus.services.SaksStatusService.test(SaksStatusService.java:39)
at no.klp.saksstatus.services.SaksStatusService$$FastClassBySpringCGLIB$$fcbe12b7.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
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.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at no.klp.saksstatus.services.SaksStatusService$$EnhancerBySpringCGLIB$$db202906.test(<generated>)
at no.klp.saksstatus.TestServlet.doGet(TestServlet.java:49)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1287)
at [internal classes]
Caused by: <openjpa-2.2.1-r422266:1396819 nonfatal user error> org.apache.openjpa.persistence.TransactionRequiredException: Can only perform operation while a transaction is active.
at org.apache.openjpa.kernel.BrokerImpl.assertActiveTransaction(BrokerImpl.java:4694)
at org.apache.openjpa.kernel.DelegatingBroker.assertActiveTransaction(DelegatingBroker.java:1386)
at org.apache.openjpa.persistence.EntityManagerImpl.flush(EntityManagerImpl.java:662)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
at com.sun.proxy.$Proxy38.flush(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:293)
at com.sun.proxy.$Proxy38.flush(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.flush(SimpleJpaRepository.java:486)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
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.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 23 more
One difference from using JPA transaction manager, is the only SELECT statments are logged. The INSERT statement is not executed (when using JPA Transaction Manager, they where all logged).
The save entry (saksStatusDao.save(new SaksStatus("100"));) should create an INSERT. And to the end a DELETE should be executed.
Everything seems very fine, but the last flush() is starting the rollback, please give me some advice to solve this. Have been struggeling with this for a month now ....
Using JPA transaction manager is not a option as I want to use JTA and allowCustomIsolationLevels to utilize UNCOMITTED_READ.
/Bjørn-Willy Arntzen, Oslo, Norway

Resources