2

So I have a Spring Batch Project has one repeated step.

<batch:job id="fooJob">
    <batch:step id="barStep">
        <batch:tasklet>
            <batch:chunk reader="myReader" writer="myWriter"
                commit-interval="5">
            </batch:chunk>
        </batch:tasklet>
    </batch:step>
</batch:job>

The reader is a JdbcCursorItemReader that also has a RowMapper to store the information it retrieves from the database into a POJO. Then "myWriter" writes the fields set in the POJO to a text file. And this happens regularly (dictated by cron).

How do I set a condition to skip the itemWriter altogether when the database is empty and the reader can't read anything?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
LargeCrimsonFish
  • 233
  • 2
  • 7
  • 15

1 Answers1

4

In a chunk oriented tasklet, everything is processed in chunks of items, not will all the items. To skip when the reader didn't read anything, you would have to know that there are in no fact no items; encountering an empty chunk of data would not suffice since there could have been another chunk before.

A simple way around that is to simply let the step continue if nothing is read. In that case, the writer will have nothing to write. Supposing that you are using FlatFileItemWriter to write the file, you can configure it not to leave an empty file behind. This is done through the shouldDeleteIfEmpty property:

Flag to indicate that the target file should be deleted if no lines have been written (other than header and footer) on close. Defaults to false.

As such, you just need to configure your writer with that property set to true. It will delete the empty file if nothing was written.

Tunaki
  • 132,869
  • 46
  • 340
  • 423