我正在开发Spring Batch - XML to DB example
。在此示例中,我想将XML数据加载到DB中。对于当前的实现,如果我运行主程序,则XML数据已成功加载到DB中,再次运行主程序,再次将数据加载至DB中(具有先前运行的输出-对于第二次运行,它们都是重复的)。如果我不想保留旧数据,即每当我运行主代码时,我都应该将新数据(无论存在于DB中的数据)放入表中。我需要在数据库中更改什么配置?
spring-batch-context.xml
<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.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:context-datasource.xml"/>
<!-- ============= ItemReader which reads data from XML file ============= -->
<bean id="xmlItemReader" class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="resource" value="classpath:examResult.xml" />
<property name="fragmentRootElementName" value="ExamResult" />
<property name="unmarshaller">
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.websystique.springbatch.model.ExamResult</value>
</list>
</property>
</bean>
</property>
</bean>
<!-- ================ ItemWriter which writes data to database ================= -->
<bean id="databaseItemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into EXAM_RESULT(STUDENT_NAME, DOB, PERCENTAGE) values (?, ?, ?)
]]>
</value>
</property>
<!-- We need a custom setter to handle the conversion between Jodatime LocalDate and MySQL DATE -->
<property name="ItemPreparedStatementSetter">
<bean class="com.websystique.springbatch.ExamResultItemPreparedStatementSetter" />
</property>
</bean>
<!-- Optional ItemProcessor to perform business logic/filtering on the input records -->
<bean id="itemProcessor" class="com.websystique.springbatch.processor.ExamResultItemProcessor" />
<!-- Optional JobExecutionListener to perform business logic before and after the job -->
<bean id="jobListener" class="com.websystique.springbatch.utils.ExamResultJobListener" />
<!-- ==================== Actual Job ========================= -->
<batch:job id="examResultJob">
<batch:step id="step1">
<batch:tasklet transaction-manager="transactionManager">
<batch:chunk reader="xmlItemReader" writer="databaseItemWriter" processor="itemProcessor" commit-interval="10" />
</batch:tasklet>
</batch:step>
<batch:listeners>
<batch:listener ref="jobListener" />
</batch:listeners>
</batch:job>
</beans>
最佳答案
为了满足您的要求,您只需要更改查询。
您应该将学生姓名作为表格中的主键,
然后在配置文件中更改查询。
"insert into EXAM_RESULT(STUDENT_NAME, DOB, PERCENTAGE)
values (?, ?, ?) on DUPLICATE KEY UPDATE DOB = ? ,PERCENTAGE=?"
将值提供给位置参数
ExamResultItemPreparedStatementSetter
。希望这能够帮到你...