首页 > 解决方案 > 通过在 Spring Batch 中调用 .sql 文件自动创建表?

问题描述

我关注了许多链接,例如Spring Batch Framework - Auto create Batch Tablehttps://docs.spring.io/spring-boot/docs/2.0.0.M7/reference/htmlsingle/#howto-initialize-a-spring-batch -database,但这不满足我的要求

在 Spring Boot 2.0 中,我们如何调用 sql 文件(手动创建并具有所有架构详细信息)以便 Spring Batch 可以为我们手动创建它,如果架构已经存在则跳过执行?

<!-- Create meta-tables -->
<jdbc:initialize-database data-source="dataSource">
        <jdbc:script location="classpath:hsqldb/initial-query.sql" />
        <jdbc:script location="org/springframework/batch/core/schema-drop-hsqldb.sql" />
        <jdbc:script location="org/springframework/batch/core/schema-hsqldb.sql" />
 </jdbc:initialize-database>

我想做 1. 如果 Schema 已经存在,则不要创建任何表 2. 如果 schema 不存在,则创建表

项目结构

DROP TABLE IF EXISTS report;

CREATE TABLE report  (
    id INT NOT NULL PRIMARY KEY,
    date DATETIME,
    impression BIGINT,
    clicks INT,
    earning DECIMAL(12,4)
  )ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

在此处输入图像描述

应用程序属性

# Data Source
spring.datasource.url=jdbc:mysql://localhost:3306/spring_batch
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update


# SPRING BATCH (BatchProperties)
# Database schema initialization mode.
spring.batch.initialize-schema=always

# Execute all Spring Batch jobs in the context on startup.
#spring.batch.job.enabled=false

# Path to the SQL file to use to initialize the database schema.
spring.batch.schema=classpath:schema-all.sql

标签: springspring-bootspring-batch

解决方案


我观察到的是——

如果我在下面启用

spring.batch.initialize-schema=总是

然后所有的表格都很好

 +------------------------------+
    | Tables_in_test               |
    +------------------------------+
    | batch_job_execution          |
    | batch_job_execution_context  |
    | batch_job_execution_params   |
    | batch_job_execution_seq      |
    | batch_job_instance           |
    | batch_job_seq                |
    | batch_step_execution         |
    | batch_step_execution_context |
    | batch_step_execution_seq     |
  1. 如果我把下面的行那么它只创建report.xml

    spring.batch.schema=classpath:schema-all.sql

如果我们可以同时创建两者,有什么办法吗?


推荐阅读