Spring Batch Tasklet

In Spring batch we mostly use readers, writers and processor, but sometimes we don’t follow ETL pattern. For example when we want to create a temporary table to use during a job.  For these kind of cases there exists a special type of step called the tasklet. Let’s take a look at an example of the creation of a SQL table in a tasklet.

Step createTempTableStep(@Qualifier("dataSource") DataSource dataSource, StepBuilderFactory stepBuilderFactory) {
    StepBuilder createTempTable = stepBuilderFactory.get("create useless table");
    String sql = "CREATE TABLE my_useless_table\n" +
            "(\n" +
            "    my_name VARCHAR(255) NOT NULL,\n" +
            "    my_date DATE NOT NULL,\n" +
            "    money DECIMAL NOT NULL,\n" +
            "    my_useless_id BIGINT NOT NULL\n" +
     return createTempTable.tasklet((contribution, chunkContext) -> {
        new JdbcTemplate(dataSource).execute(sql);
        return RepeatStatus.FINISHED;

We can identify the following steps in the code:

  • Give the step a name.
  • Create an SQL statement for table creation.
  • Use the tasklet method on the stepBuilder. It takes 2 parameters, because the sasklet interface expects 2 parameters. We use it as a lambda.
  • We perform the action we want to perform.
  • We return the finished status.
  • We build our step which is in this case a tasklet.

This step can be used just like any other step in the creation of a job.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s