Initialize a Database Using Basic SQL Scripts
Spring Boot can automatically create the schema (DDL scripts) of your JDBC DataSource
or R2DBC ConnectionFactory
and initialize it (DML scripts). It loads SQL from the standard root classpath locations: schema.sql
and data.sql
, respectively. In addition, Spring Boot processes the schema-${platform}.sql
and data-${platform}.sql
files (if present), where platform
is the value of spring.sql.init.platform
. This allows you to switch to database-specific scripts if necessary. For example, you might choose to set it to the vendor name of the database (hsqldb
, h2
, oracle
, mysql
, postgresql
, and so on). By default, SQL database initialization is only performed when using an embedded in-memory database. To always initialize an SQL database, irrespective of its type, set spring.sql.init.mode
to always
. Similarly, to disable initialization, set spring.sql.init.mode
to never
. By default, Spring Boot enables the fail-fast feature of its script-based database initializer. This means that, if the scripts cause exceptions, the application fails to start. You can tune that behavior by setting spring.sql.init.continue-on-error
.
Script-based DataSource
initialization is performed, by default, before any JPA EntityManagerFactory
beans are created. schema.sql
can be used to create the schema for JPA-managed entities and data.sql
can be used to populate it. While we do not recommend using multiple data source initialization technologies, if you want script-based DataSource
initialization to be able to build upon the schema creation performed by Hibernate, set spring.jpa.defer-datasource-initialization
to true
. This will defer data source initialization until after any EntityManagerFactory
beans have been created and initialized. schema.sql
can then be used to make additions to any schema creation performed by Hibernate and data.sql
can be used to populate it.
If you are using a Higher-level Database Migration Tool, like Flyway or Liquibase, you should use them alone to create and initialize the schema. Using the basic schema.sql
and data.sql
scripts alongside Flyway or Liquibase is not recommended and support will be removed in a future release.
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto.data-initialization