Ashish Shetkar
Ashish Shetkar

Reputation: 1467

add multiple update queries in spring batch JdbcBatchItemWriter

I need to run update on two table based on the data i received in my file. The source is one single file.

I tried searching for JdbcBatchItemWriter with multiple queries.

Currently i tried below approach with 1 job and 2 steps - where am using same reader, same processor and same listener in both of the steps - but i think it is repetitive.

<batch:job id="batchJob">

    <batch:step id="step1" next="step2">
        <batch:tasklet>

            <batch:chunk reader="cvsFileItemReader" processor="myItemProcessor"
                writer="mysqlItemWriter1" commit-interval="1" skip-limit="10">
                <batch:listeners>
                    <batch:listener ref="stepListener">
                    </batch:listener>
                </batch:listeners>
            </batch:chunk>
        </batch:tasklet>
    </batch:step>

    <batch:step id="step2">
        <batch:tasklet>
            <batch:chunk reader="cvsFileItemReader" processor="myItemProcessor"
                writer="mysqlItemWriter2" commit-interval="1" skip-limit="10">
                <batch:listeners>
                    <batch:listener ref="stepListener">
                    </batch:listener>
                </batch:listeners>
            </batch:chunk>
        </batch:tasklet>
    </batch:step>

</batch:job>

My itemWriter1 and 2 run update and i need to get the update count for both queries.

This is just i work around i found out , but i think this is not optimal enough

Please let me know if we can use multiple update queries in one single writer. Also suggest if any optimal way.

Thank you

Upvotes: 1

Views: 1528

Answers (1)

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18403

You may approach the problem decorating JdbcBatchItemWriter: this decorator is responsible to store in ExecutionContext how many items the real writer really write so you can get back later in your step.

class CountingItemWriter implements ItemStreamWriter {
  private JdbcBatchItemWriter delegate;
  private int count = 0;
  private final String id;

  CountingItemWriter(String id) {
    this.id = "CountingItemWriter#"+id;
  }

  write(List<?> items) {
    delegate.write(items);
    count += items.size();
  }

  open(ExecutionContext ec) {
    count = getInt(this.id, 0);
  }

  update(ExecutionContext ec) {
    ec.putInt(this.id, count);
  }

  close() {
    // no-op
  }
}

Remember to give a different id if you have more than one writer to be able to retrieve the right counter for every writer.

Upvotes: 1

Related Questions