Reading Records From a Database in Spring Batch

半世苍凉 提交于 2020-01-01 19:12:27

问题


I'm trying to read some records from a database using loops then do some calculations on the records (updating a field called total).

But i'm new to spring batch so please can anyone provide me with some tips.


回答1:


this sounds like something the chunk pattern would address. you can use re-use existing Spring Batch components to read from the database, compose your own processor, then pass back to a Spring Batch component to store.

say the use case is like this; - read a record - record.setTotalColumn(record.getColumn2() + record.getColumn3()) - update

this configuration might look like this

<batch:job id="recordProcessor">
  <batch:step id="recordProcessor.step1">
    <batch:tasklet>
      <batch:chunk reader="jdbcReader" processor="calculator" writer="jdbcWriter" commit-interval="10"/>
      </batch:tasklet>
  </batch:step>
</batch:job>

<bean id="jdbcReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
  <property name="dataSource" ref="dataSource"/>
  <property name="sql" value="select idColumn,column1,column2,totalColumn from my_table"/>
  <property name="rowMapper" ref="myRowMapper"/>
</bean>

<bean id="jdbcWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
  <property name="dataSource" ref="dataSource"/>
  <property name="sql" value="update my_table set totalColumn = :value where idColumn = :id"/>
</bean>

<bean id="calculator" class="de.incompleteco.spring.batch.step.item.CalculationProcessor"/>

this means that the only thing you have to 'write' from scratch would be the calculator processor which could e something like this;

package de.incompleteco.spring.batch.step.item;

import org.springframework.batch.item.ItemProcessor;

public class CalculationProcessor implements ItemProcessor<MyObject, MyObject> {

    @Override
    public MyObject process(MyObject item) throws Exception {
        //do the math
        item.setTotalColumn(item.getColumn1() + item.getColumn2());
        //return
        return item;
    }

}


来源:https://stackoverflow.com/questions/16167717/reading-records-from-a-database-in-spring-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!