简体   繁体   English

Tasklet 在 spring 批处理中删除表

[英]Tasklet to delete a table in spring batch

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 that will delete the table directly from the job xml file ?有没有什么简单的方法可以编写一个直接从作业 xml 文件中删除表的 tasklet?

I am using ibatis as ORM我使用 ibatis 作为 ORM

you mean even more simple than a tasklet, eg like this pseudocode ?你的意思是比 tasklet 更简单,例如像这个伪代码?

<!-- 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;
}
}

For batch Java config.用于批处理 Java 配置。 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):脚本(SQL 服务器):

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";

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.仅供参考,您可以使用<jdbc:initialize-database>指向一个初始化脚本,其中包含用于初始化数据库的所有 SQL 查询,而不是 tasklet。 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">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM