org.springframework.dao.DataAccessResourceFailureException: Unable to write to file resource: [class path resource [report.xml]]; Spring Batch - spring

I am developing Spring Batch - MongoDB to XML example. I have successfully developed the code, when I run the my main program. I see the following eror comes. I am not sure what is going wrong. I followed many links, but I dont see its not working fine.
org.springframework.dao.DataAccessResourceFailureException: Unable to write to file resource: [class path resource [report.xml]]; nested exception is java.io.FileNotFoundException: class path resource [report.xml] cannot be resolved to URL because it does not exist
at org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:436) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:400) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:96) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.open(TaskletStep.java:310) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:197) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at com.mkyong.App.main(App.java:21) [classes/:na]
Caused by: java.io.FileNotFoundException: class path resource [report.xml] cannot be resolved to URL because it does not exist
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:187) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:48) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.batch.item.xml.StaxEventItemWriter.open(StaxEventItemWriter.java:427) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
... 15 common frames omitted
13:21:05.358 [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
13:21:05.367 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.368 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#5b202a3a]
13:21:05.368 [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
13:21:05.375 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.375 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#5669c5fb]
13:21:05.379 [main] ERROR o.s.batch.core.step.AbstractStep - Exception while closing step execution resources in step step1 in job reportJob
java.lang.NullPointerException: null
at org.springframework.batch.item.xml.StaxEventItemWriter.close(StaxEventItemWriter.java:659) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:85) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.close(TaskletStep.java:305) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:271) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:134) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at com.mkyong.App.main(App.java:21) [classes/:na]
13:21:05.381 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution complete: StepExecution: id=1, version=2, name=step1, status=FAILED, exitStatus=FAILED, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=0, rollbackCount=0
13:21:05.381 [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
13:21:05.383 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.383 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#178213b]
13:21:05.383 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.step1 with status=FAILED
13:21:05.385 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Handling state=reportJob.fail0
13:21:05.385 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.fail0 with status=FAILED
13:21:05.388 [main] DEBUG o.s.batch.core.job.AbstractJob - Job execution complete: JobExecution: id=0, version=1, startTime=Sun Jan 08 13:21:05 IST 2017, endTime=null, lastUpdated=Sun Jan 08 13:21:05 IST 2017, status=FAILED, exitStatus=exitCode=FAILED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[reportJob]], jobParameters=[{}]
13:21:05.388 [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
13:21:05.397 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
13:21:05.397 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#2d36e77e]
13:21:05.397 [main] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [FlowJob: [name=reportJob]] completed with the following parameters: [{}] and the following status: [FAILED]
Exit Status : FAILED
Done
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:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- connect to mongodb -->
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="yourdb" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<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.Report" />
<property name="query" value="" />
<property name="sort">
<util:map id="sort">
<entry key="id" value="" />
</util:map>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<!-- <property name="resource" value="classpath:xml/report.xml" /> -->
<property name="resource" value="report.xml" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="record" />
</bean>
<!-- ==== Solution-1 ==== -->
<bean id="reportMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>com.mkyong.Report</value>
</property>
</bean>
<!-- ==== Solution-2 ==== -->
<!-- <bean id="reportMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="aliases">
<util:map id="aliases">
<entry key="record" value="com.mkyong.Report" />
</util:map>
</property>
<property name="converters">
<array>
<ref bean="reportConverter" />
</array>
</property>
</bean> -->
<bean id="reportConverter" class="com.mkyong.ReportConverter" />
</beans>
Report.java
#XmlRootElement(name = "record")
public class Report {
private int id;
private Date date;
private long impression;
private int clicks;
private BigDecimal earning;
#XmlAttribute(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#XmlElement(name = "impression")
public long getImpression() {
return impression;
}
public void setImpression(long impression) {
this.impression = impression;
}
#XmlElement(name = "clicks")
public int getClicks() {
return clicks;
}
public void setClicks(int clicks) {
this.clicks = clicks;
}
#XmlElement(name = "earning")
public BigDecimal getEarning() {
return earning;
}
public void setEarning(BigDecimal earning) {
this.earning = earning;
}
}
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");
}
}
Looking forward to get the response.

It looks like the resource value for xmlItemWriter is incorrect. You can provide a classpath or file/URL.
See "Table 8.1. Resource strings" at this link http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html#resources-resourceloader

Related

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>

spring batch AsynchJob Launcher ,Error in setting job repo

Hi below is my configuration for creating asynchlob launcher
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="&jobRepository" />
<property name="taskExecutor" ref="taskExecutor" />
</bean>
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean" />
i'm getting below error
Error creating bean with name 'batchJobLauncher': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.launch.support.SimpleJobLauncher com.batch.launcher.BatchJobLauncher.asyncJobLauncher; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/BatchConfig.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean' to required type 'org.springframework.batch.core.repository.JobRepository' for property 'jobRepository'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
.....
caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean' to required type 'org.springframework.batch.core.repository.JobRepository' for property 'jobRepository'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:476) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1523) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1482) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 54 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:287) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:461) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 60 more
i tried without & also.
error like this
13:58:59,346 WARN [org.springframework.web.context.support.XmlWebApplicationContext] (ServerService Thread Pool -- 58) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobBuilders' defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.configuration.annotation.JobBuilderFactory]: Factory method 'jobBuilders' threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean$$EnhancerBySpringCGLIB$$99e29281 cannot be cast to org.springframework.batch.core.repository.JobRepository
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
Here is a working example made from http://www.mkyong.com/spring-batch/spring-batch-hello-world-example/ and tested on wildfly 9.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
">
<bean id="report" class="Report" scope="prototype" />
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<batch:job id="helloWorldJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="cvsItemReader" writer="xmlItemWriter"
commit-interval="10">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
<property name="taskExecutor" ref="taskExecutor" />
</bean>
<bean id="cvsItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="classpath:report.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="id,sales,qty,staffName,date" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="report" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:/home/username/report.xml" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="report" />
</bean>
<bean id="reportMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>Report</value>
</list>
</property>
</bean>
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
</beans>
Report.java:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "record")
public class Report {
private int id;
private String sales;
private int qty;
private String staffName;
private String date;
#XmlAttribute(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "sales")
public String getSales() {
return sales;
}
public void setSales(String sales) {
this.sales = sales;
}
#XmlElement(name = "qty")
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
#XmlElement(name = "staffName")
public String getStaffName() {
return staffName;
}
public void setStaffName(String staffName) {
this.staffName = staffName;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return "Report [id=" + id + ", sales=" + sales
+ ", qty=" + qty + ", staffName=" + staffName + "]";
}
}
To run use a servlet with the following code:
ApplicationContext context =
new ClassPathXmlApplicationContext("job.xml");
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("helloWorldJob");
try {
org.springframework.batch.core.JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}

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.

Could not roll back transaction using Hibernate Template

I am using Spring 3.1 and Hibernate 3.0 with the below configuration to test the Declarative Transactions, but am not able to see the roll back statements.
Here i have noticed, every time it is opening a new session. I guess this may cause the issue.
Is there anything wrong in my config / code..?
{
Log
----
09:40:54.909 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
09:40:54.914 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [save*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-SNTransException]
09:40:54.914 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [get*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly]
09:40:54.914 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]
09:40:54.936 [main] DEBUG o.s.o.hibernate3.SessionFactoryUtils - Opening Hibernate Session
09:40:54.960 [main] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13750710549
09:40:54.978 [main] DEBUG o.h.e.def.AbstractSaveEventListener - executing identity-insert immediately
09:40:54.979 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
09:40:54.979 [main] DEBUG org.hibernate.jdbc.ConnectionManager - opening JDBC connection
09:40:54.979 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/test]
09:40:54.992 [main] DEBUG org.hibernate.SQL - insert into springtrans.users (username, password, status) values (?, ?, ?)
Hibernate: insert into springtrans.users (username, password, status) values (?, ?, ?)
09:40:55.009 [main] DEBUG o.h.id.IdentifierGeneratorFactory - Natively generated identity: 458
09:40:55.009 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
09:40:55.013 [main] DEBUG o.s.orm.hibernate3.HibernateTemplate - Eagerly flushing Hibernate session
09:40:55.014 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades
09:40:55.014 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections
09:40:55.018 [main] DEBUG org.hibernate.engine.Collections - Collection found: [com.snsystems.data.Users.userSettingses#458], was: [<unreferenced>] (initialized)
09:40:55.031 [main] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13750710550
09:40:55.032 [main] DEBUG o.h.e.def.AbstractSaveEventListener - executing identity-insert immediately
09:40:55.032 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
09:40:55.032 [main] DEBUG org.hibernate.jdbc.ConnectionManager - opening JDBC connection
09:40:55.032 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/test]
09:40:55.047 [main] DEBUG org.hibernate.SQL - insert into springtrans.user_settings (user_id, last_login_ip, failed_logins) values (?, ?, ?)
Hibernate: insert into springtrans.user_settings (user_id, last_login_ip, failed_logins) values (?, ?, ?)
09:40:55.055 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
09:40:55.061 [main] DEBUG o.h.util.JDBCExceptionReporter - could not insert: [com.snsystems.data.UserSettings] [insert into springtrans.user_settings (user_id, last_login_ip, failed_logins) values (?, ?, ?)]
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'last_login_ip' cannot be null
}
applicationContext.xml
{
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>/jdbc.properties</value></property>
</bean>
<!-- Data Source -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<!-- Spring hibernate integration -->
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Transaction Template Bean -->
<bean id="transactionTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref local="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="view*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>/com/snsystems/data/Users.hbm.xml</value>
<value>/com/snsystems/data/UserSettings.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="usersDao" class="com.snsystems.dao.impl.UsersDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="userSettingsDao" class="com.snsystems.dao.impl.UserSettingsDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="userService" class="com.snsystems.service.impl.UsersServiceImpl">
<property name="usersDao" ref="usersDao" />
<property name="userSettingsDao" ref="userSettingsDao" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" rollback-for="SNTransException"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServiceOperation" expression="execution(* com.snsystems.service..Service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServiceOperation"/>
</aop:config>
}
UsersDaoImpl
public class UsersDaoImpl implements IUsersDao {
private HibernateTemplate hibernateTemplate;
public void saveOrUpdateUsers(Users users) throws PersistenceException {
try {
hibernateTemplate.saveOrUpdate(users);
} catch (Exception e) {
throw new PersistenceException(e);
}
}
public void deleteUsers(Users users) throws PersistenceException {
try {
hibernateTemplate.delete(users);
} catch (Exception e) {
throw new PersistenceException(e);
}
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
UsersServiceImpl
public class UsersServiceImpl implements IUsersService
{
private IUsersDao usersDao = null;
private IUserSettingsDao userSettingsDao = null;
public void saveOrUpdateUsers(Users users) throws SNTransException {
try {
usersDao.saveOrUpdateUsers(users);
} catch (PersistenceException e) {
throw new SNTransException(e);
}
}
public void deleteUsers(Users users) throws SNTransException {
try {
usersDao.deleteUsers(users);
} catch (PersistenceException e) {
throw new SNTransException(e);
}
}
public void saveOrUpdateUserSettings(UserSettings userSettings) throws SNTransException {
try {
userSettingsDao.saveOrUpdateUserSettings(userSettings);
} catch (PersistenceException e) {
throw new RuntimeException(e);
}
}
public void deleteUserSettings(UserSettings userSettings) throws SNTransException {
try {
userSettingsDao.deleteUserSettings(userSettings);
} catch (PersistenceException e) {
throw new SNTransException(e);
}
}
.. setters and getters for dao's
}
UsersServiceTest
{
public class UsersServiceTest {
private static ClassPathXmlApplicationContext context = null;
private static IUsersService usersService = null;
private static Users users = null;
private static UserSettings userSettings = null;
#Before
public void setUp() {
try {
context = new ClassPathXmlApplicationContext("applicationContextBack.xml");
usersService = (IUsersService) context.getBean("userService");
} catch (Exception e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
usersService = null;
context = null;
}
#Test
public void testSaveOrUpdateUserSettings() throws Exception {
users = new Users();
users.setUsername("JUnitTest");
users.setPassword("JUnitTest");
users.setStatus("inactive");
usersService.saveOrUpdateUsers(users);
assertNotNull("User Id is null", users.getId());
userSettings = new UserSettings();
userSettings.setUsers(users);
usersService.saveOrUpdateUserSettings(userSettings);
assertNotNull("UserSettings Id is null", userSettings.getId());
}
}
}
You should add #Transactional annotation to your service (impl) methods.
Example:
#Transactional
public void saveOrUpdateUsers(Users users) {
...
}
so you want spring transaction manager to roll back transaction after each test? then the Spring TestContext Framework may help
add annotation to your test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("applicationContext.xml")
#Transactional
public class UsersServiceTest {
}
spring transaction manager will automatically start a new transaction before test and rollback it when test finishes

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