简体   繁体   中英

Spring JPA ddl-auto=create with initial data

I want to create my tables using Spring JPA auto table creation after that I want to insert my own data (SQL).

To be able to do this I used these lines in my application.properties

spring.jpa.hibernate.ddl-auto=create

spring.sql.init.data-locations=\
classpath:database/sectors_data.sql,\
classpath:database/users_data.sql
spring.sql.init.mode=always

The problem is that when I use ddl-auto=create and run my application it creates tables but does not insert data. To make it to insert data I should change ddl-auto=create to ddl-auto=update and run my application again.

I want to know is there a way to make it with only one run, create tables and then insert data without using any db migration tools like Flyway .

Thanks for answers.

Please note that script-based initialization ie through schema.sql and data.sql and Hibernate initialization together can cause some issues.

Either we disable Hibernate automatic schema creation:

spring.jpa.hibernate.ddl-auto=none

This will ensure that script-based initialization is performed using schema.sql and data.sql directly.

If we still want to have both Hibernate automatic schema generation in conjugation with script-based schema creation and data population, we'll have to use:

spring.jpa.defer-datasource-initialization=true

This will ensure, that after Hibernate schema creation is performed then additionally schema.sql is read for any additional schema changes and data.sql is executed to populate the database.

Also, script-based initialization is performed by default only for embedded databases, to always initialize a database using scripts, we'll have to use:

spring.sql.init.mode=always

refer spring-boot-data-sql-and-schema-sql also refer official Spring documentation Initialize a Database Using Basic SQL Scripts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM