Tasklet to delete a table in spring batch

后端 未结 3 767
借酒劲吻你
借酒劲吻你 2020-12-12 03:45

I have steps in the batch job that does different things.

But before I begin all these steps, I need to clear a table. Is there any simple way to write a tasklet tha

相关标签:
3条回答
  • 2020-12-12 04:13

    For batch Java config. Step:

    @Bean
    private Step dropTable() {
      return stepBuilderFactory
        .get("dropTable")
        .transactionManager(transactionManager)
        .tasklet(dropTableTasklet())
        .build();
    }
    

    Tasklet:

    private Tasklet dropTableTasklet() {
      return (contribution, chunkContext) -> {
        new JdbcTemplate(this.dataSource).execute(DROP_SCRIPT);
        return RepeatStatus.FINISHED;
      };
    }
    

    Script (SQL server):

    private static final String DROP_SCRIPT = "IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES "
      + "WHERE TABLE_NAME = 'some_table') "
      + "BEGIN "
      + " DROP TABLE some_table "
      + "END";
    
    0 讨论(0)
  • 2020-12-12 04:28

    you mean even more simple than a tasklet, e.g. like this pseudocode ?

    <!-- xml bean config -->
    <bean id="deleteTableTaskletStep" class="...">
       <property name="dataSource" ref="dataSource" />
       <property name="sql" value="delete from ..." />
    </bean>
    
    // java code
    public class DeleteTableTasklet implements Tasklet {
    
    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        new JdbcTemplate(this.dataSource).executeQuery(this.sql)
        return RepeatStatus.FINISHED;
    }
    }
    
    0 讨论(0)
  • 2020-12-12 04:37

    FYI, Instead of a tasklet, you can use the <jdbc:initialize-database> to point to an initialization script with all your SQL queries used to initialize the db. That way, the queries will be easier to maintain.

    <!-- xml bean config -->
    <jdbc:initialize-database data-source="dataSource">
           <jdbc:script location="file:C:/db/initial-query.sql" />
    </jdbc:initialize-database>
    

    Just remember to include this at the top

    <beans xmlns="http://www.springframework.org/schema/beans"
           ...
           xmlns:jdbc="http://www.springframework.org/schema/jdbc"
           xsi:schemaLocation="...
               http://www.springframework.org/schema/jdbc
               http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd">
    
    0 讨论(0)
提交回复
热议问题