springboot quartz init schema only on first startup

Viewed 131

This is my config:

@Bean
    @QuartzDataSource
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource quartzDataSource() {
        return DataSourceBuilder.create().build();
    }

and this is my app.yml:

datasource:
    url: my-url
    jdbcUrl: ${spring.datasource.url}
    username: 'root'
    password: 'root'
...
quartz:
    job-store-type: jdbc
    jdbc:
      initialize-schema: always
    wait-for-jobs-to-complete-on-shutdown: true
    properties:
      org:
        quartz:
          dataSource:
            quartz-data-source:
              provider: hikaricp
              driver: com.mysql.cj.jdbc.Driver
              URL: ${spring.datasource.url}
              user: ${spring.datasource.username}
              password: ${spring.datasource.password}
              maximumPoolSize: 5
              connectionTestQuery: SELECT 1
              validationTimeout: 5000
              idleTimeout: 1
          scheduler:
            instanceId: AUTO
            instanceName: my-project-scheduler
          jobStore:
            class: org.quartz.impl.jdbcjobstore.JobStoreTX
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
            useProperties: false
            misfireThreshold: 60000
            clusterCheckinInterval: 30000
            isClustered: true
            dataSource: quartz-data-source
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool
            threadCount: 1
            threadPriority: 5
            threadsInheritContextClassLoaderOfInitializingThread: true

My question:

If I set initialize-schema: always then the qrtz tables are created on each application startup.

On the other side, if I set initialize-schema: never then I get an error on the first startup that the qrt tables are missing.

Is there a way to configure it to initialize the qrtz tables only if they do not exist?

1 Answers

You are gonna need a migration tool to handle the database creation.

Spring Boot provides two options: Flyway and LiquidBase.

Choose one, create migration scripts and you are up and running.

I personally like the Flyway approach.

You just add implementation 'org.flywaydb:flyway-core' to your build.gradle file (or the maven alternative).

Then add this to your application.yml

spring:
  flyway:
    enabled: true
    baseline-on-migrate: true

Then create db/migration folder in resources folder and put in your migration scripts eg. V1_0_0__db_init.sql (flyway has its own naming convention).

To get the create SQL scripts I recommend that you export them from running database.

Also do not forget to change the spring.jpa.hibernate.ddl-auto to validate.

Related