Spring Batch Framework - Auto create Batch Table

With Spring Boot 2.0 you probably need this: https://docs.spring.io/spring-boot/docs/2.0.0.M7/reference/htmlsingle/#howto-initialize-a-spring-batch-database

spring.batch.initialize-schema=always

By default it will only create the tables if you are using an embedded database.

Or

 spring.batch.initialize-schema=never

To permanently disable it.


Spring Batch uses the database to save metadata for its recover/retry functionality.

If you can't create tables in the database then you have to disable this behaviour

If you can create the batch metadata tables but not in runtime then you might create them manually


Spring Batch required following tables to run job

  • 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

If you are using h2 db then it will create all required table by default

  • spring.h2.console.enabled=true
  • spring.datasource.url=jdbc:h2:mem:testdb
  • spring.datasource.driverClassName=org.h2.Driver
  • spring.datasource.username=sa
  • spring.datasource.password=
  • spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

When you start using Mysql or any other database you need to add follwing properties into application.properties

               spring.batch.initialize-schema=always

To enable auto create spring batch data-schema simply add this line to your spring application.properties file :

spring.batch.initialize-schema=always

To understand more about Spring batch meta-data schema :

https://docs.spring.io/spring-batch/trunk/reference/html/metaDataSchema.html


Seems silly, but someone can have the same problem.

I was receiving this error after drop all tables from a database. When I tried to start the Spring Batch, I received the error:

bad SQL grammar [SELECT JOB_INSTANCE_ID, JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? and JOB_KEY = ?]

and:

Invalid object name 'BATCH_JOB_INSTANCE'

This happened to me because I drop the tables without restart the service. The service was started and receive the database metadata with the Batch tables on the database. After drop them and not restart the server, the Spring Batch thought that the tables still exists.

After restart the Spring Batch server and execute the batch again, the tables were created without error.