Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
11
Help us understand the problem. What is going on with this article?
@tera78

Spring-Batch FlatFileItemWriterの使い方

More than 5 years have passed since last update.

Spring-BatchにおけるFlatFileItemWriterの実装方法に関して、ググッても全く出てこなかったので仕方なくライブラリのソースを読みつつ実装したので以下に残す。

SampleAggregator.java
public class SampleAggregator implements LineAggregator<SampleInputDto>{

    @Override
    public String aggregate(SampleInputDto item) {
        StringBuilder sb = new StringBuilder();
        sb.append(item.getParam1());
        sb.append(",");
        sb.append(item.getParam2());
        sb.append(",");
        sb.append(item.getParam3());
        return sb.toString();
    }
}
SampleBatchConfiguration.java
    @Bean
    public FlatFileItemWriter<SampleOutputDto> writer() {
        FlatFileItemWriter<SampleOutputDto> writer = new FlatFileItemWriter<SampleOutputDto>();
        writer.setResource(new FileSystemResource("C:¥tenp¥sample-data.csv"));
        writer.setLineAggregator(new SampleAggregator()); 
        return writer;
    }

はまったのは、以下の1点。

LineAggregatorインターフェースをimplementsして、aggregateメソッドを@OverrideしたクラスのインスタンスをsetLineAggregator()で設定しないと(確か)IllegalArgumentExceptionが発生する

@Overrideするaggreageteメソッドの実装内容は、引数に入力のPOJOが渡されるので、ファイルの1行出力内容をString型で返却してやれば良い。

■補足
Java8ならラムダ式が使えるので、いちいちSampleAggregatorクラスを実装するのが面倒くさい場合、以下のようにも書ける。

SampleBatchConfiguration.java
    @Bean
    public FlatFileItemWriter<SampleOutputDto> writer() {
        FlatFileItemWriter<SampleOutputDto> writer = new FlatFileItemWriter<SampleOutputDto>();
        writer.setResource(new FileSystemResource("C:¥tenp¥sample-data.csv"));
        writer.setLineAggregator(item -> {
                StringBuilder sb = new StringBuilder();
            sb.append(item.getParam1());
            sb.append(",");
            sb.append(item.getParam2());
            sb.append(",");
            sb.append(item.getParam3());
            return sb.toString();
        });
        return writer;
    }

以下参考
http://www.mybatis.org/spring/ja/batch.html

11
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
tera78
フリーでWeb系エンジニアの傍ら、空論リリックというバンドでDrしてます。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
11
Help us understand the problem. What is going on with this article?