gpt4 book ai didi

java - Spring Batch ItemWriter Java

转载 作者:行者123 更新时间:2023-11-30 06:17:12 24 4
gpt4 key购买 nike

我正在尝试使用SpringBoot编写spring批处理。首先,程序将从数据库中读取数据,然后将其写入.csv格式的文件。

这是我尝试过的代码

阅读器

    @Bean
public ItemReader<A> Reader() throws Exception {
List list = new ArrayList<>();
JdbcCursorItemReader<A> reader = new JdbcCursorItemReader<A>();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

String sql = "SELECT ID AS id FROM TABLE_A ";
list = jdbcTemplate.query(sql, new Mapper()); // store all retrieved data to list
reader.setSql(sql);
reader.setDataSource(dataSource);
reader.setRowMapper(new Mapper());

if (list != null) {
for (A c : (List<A>) list) {
c.setId("123"); // overwrite the id
c.setState("Active");
}
}
return reader;
}

映射器

   public class Mapper implements RowMapper<A> {

@Override
public A mapRow(ResultSet rs, int rowNum) throws SQLException {

A c = new A();
c.setId(rs.getString("id"));
}

作者

    @Bean
public ItemWriter<A> Writer() {
FlatFileItemWriter<A> csvFileWriter = new FlatFileItemWriter<>();
String exportFileHeader = "ID" + delimiter + "State";
StringHeaderWriter headerWriter = new StringHeaderWriter(exportFileHeader);
csvFileWriter.setHeaderCallback(headerWriter);
headerWriter.checkRepository();

String exportFilePath = "/home/xxx/Desktop/outputs/" + fileName + time() + ".csv";
csvFileWriter.setResource(new FileSystemResource(exportFilePath));
LineAggregator<A> lineAggregator = createStudentLineAggregator();
csvFileWriter.setLineAggregator(lineAggregator);
return csvFileWriter;
}

批量配置

  @Bean
public Job job() throws Exception {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.start(step1())
.build();
}


@Bean
public Step step1() throws Exception {
return stepBuilderFactory.get("step1")
.<A, A>chunk(1)
.reader(Reader())
.processor(new Processor())
.writer(Writer())
.build();
}

处理器

public class Processor implements ItemProcessor<A, A> {

@Override
public A process(A i) throws Exception {
System.out.println("Processing..." + i);
return i;
}
}

当我检查生成的文件时,我可以看到数据库中的值 id,但看不到 123。状态的值也是空的。如何覆盖映射值?

最佳答案

在 Spring Batch Reader 中只负责读取数据。如果你想操作数据,它必须在处理器中完成。所以:

public class Processor implements ItemProcessor<A, A> {

@Override
public A process(A i) throws Exception {
System.out.println("Processing..." + i);
i.setId("123");
i.setStatus("Active");
return i;
}
}

这部分代码

    list = jdbcTemplate.query(sql, new Mapper()); // store all retrieved data to list

if (list != null) {
for (A c : (List<A>) list) {
c.setId("123"); // overwrite the id
c.setState("Active");
}
}

实际上什么也不做。在 Reader() 中,您应该只返回配置的阅读器。您可以通过以下方式正确配置:

    reader.setSql(sql);
reader.setDataSource(dataSource);
reader.setRowMapper(new Mapper());

关于java - Spring Batch ItemWriter Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48960162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com