问题
We're storing the elements of a XML file into our database using spring batch. Is it possible to retrieve the number of the element being processed when inserting it into the database?
To clearify, this is my job configuration:
<bean id="xmlItemReader" scope="step"
class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="fragmentRootElementName" value="person" />
<property name="resource" value="#{jobParameters[xmlPath]}" />
<property name="unmarshaller" ref="personUnmarshaller" />
</bean>
<!-- Read and map values to object, via jaxb2 -->
<bean id="personUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.batch.input.Person</value>
</list>
</property>
</bean>
<bean id="personItemWriter" scope="step"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into PERSON (
ID_XML, PERSON_ID, ITEM_NUM,
NAME, SURNAME1, SURNAME2)
values (
#{jobParameters[ID_XML]}, :personID,
#{stepExecution.writeCount}, -- This is what we want
:name, :surname1, :surname2)
]]>
</value>
</property>
<!-- It will take care matching between object property and sql name parameter -->
<property name="itemSqlParameterSourceProvider">
<bean
class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
</property>
</bean>
As you can see, we have try to get this number using stepExecution.writeCount, but it always returns 0, also with the readCount property.
A database sequence is not the solution because it has to be the number inside the current XML file, starting with 0.
It has to be independent of the chunk being processed because the auto-commit. Our auto-commit is 1000. If we have 10000 elements, we need to store the numbers from 0 to 9999, and not 10 groups from 0 to 999.
The order inside the XML file is not important, we just need to number the elements.
Any help? Thanks
回答1:
Check ItemCountAware: let Person implements this interface and use Person.itemCount property as sql parameter value.
来源:https://stackoverflow.com/questions/25177024/spring-batch-how-to-get-the-number-of-the-element-being-processed