Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

Spring Batch - Map and Write 1->Many rows

I have a spreadsheet that looks like so...

    US LC   US MC
40  55.39   3.26
39  54.39   1.26

This is it's POJO:

@Data
public class ExcelObject {
    private BigDecimal timePeriod;
    private BigDecimal usLc;
    private BigDecimal usMc;
}

I need to transform this sheet and save it to the database like so...

TIME_PERIOD, LABEL, ALLOCATION
40, "US LC", 55.39
40, "US MC",  3.26
39, "US LC", 54.39
39, "US MC",  1.26

This is the POJO for the transformed ExcelObject:

@Data
public class ExcelItem {
    private BigDecimal timePeriod;
    private String label;
    private BigDecimal allocation;
}

What's the best Spring Batch strategy to accomplish this transformation? I have a row mapper to map the data as-is from the spreadsheet. I was thinking in my processor I'd make the transformation. But how do I return 4 results from the processor, and write 4 rows? Thanks.

question from:https://stackoverflow.com/questions/65853077/spring-batch-map-and-write-1-many-rows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Implement an ItemReader to read ExcelObject :

public class MyItemReader implements ItemReader<ExcelObject>  {

    @Override
    ExcelObject read() {

    }
}

Then an ItemProcessor to convert ExcelObject to a List<ExcelItem> :

public class MyItemProcessor implements ItemProcessor<ExcelObject,List<ExcelItem>> {
    
    @Override
    List<ExcelItem> process(ExcelObject){

    }

}

Finally , an ItemWriter to write List<ExcelItem>. In the writer , you can loop the items and reuse an existing ItemWriter provided by spring-batch and delegate to it for writing an item such as :

public class MyItemWriter implements ItemWriter<List<ExcelItem>> {

        @Autowired
        private JdbcBatchItemWriter<ExcelItem> jdbcWriter;
    
        @Override
        public void write(List<List<ExcelItem>> items) throws Exception {
            
            for(List<ExcelItem> item : items){
                jdbcWriter.writer(item);
            }
        }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...