如何在Spring批处理应用程序启动时将数据插入表中

时间:2018-02-06 10:51:20

标签: spring initialization spring-batch startup

我是Spring Batch编程的新手,并坚持以下方案。

我有一个Spring Batch应用程序,我希望每次应用程序启动时都运行一个SQL INSERT脚本。

场景:

My Spring批处理应用程序有2个数据库 - (1)HSQL和(2)MySQL Spring批处理内部的所有表都是在HSQL中创建的,应用程序所需的所有表都存在于MySQL中。我希望每次应用程序启动时都在MySQL中运行INSERT SQL脚本。

我浏览了很多文章,并且正如在data.sqldata-mysql.sql创建的大多数文章中所建议的那样,并运行了我的应用。但它尝试在HSQL中搜索表并抛出对象未找到异常

我有没有办法执行SQL脚本,以便它会尝试连接到MySQL,然后进行插入。

非常感谢帮助。

提前致谢 Saurabh

1 个答案:

答案 0 :(得分:0)

您可以使用JobExecutionListener.beforeJob 听众以及Spring ScriptUtils

示例代码:

public class MyobListener implements JobExecutionListener {
@Autowired
Private DataSource yourMySQLDataSource 

   //This method will be called before job get started 
    @Override
    public void beforeJob(JobExecution jobExecution) {
    ScriptUtils.executeSqlScript(yourMySQLDataSource.getConnection(), new ClassPathResource("your.sql"));

    }

    @Override
    public void afterJob(JobExecution jobExecution) {   

    }
}

参考ScriptUtil