简体   繁体   中英

Generating sample database data via Spring data.sql file

I would like to initialize my postgres database with data.sql file. I have created queries like:

insert into network_hashrate (
   rep_date, hashrate
) 
select
   date_from - (s.a || ' hour')::interval,
   s.a::double precision
from generate_series(0, 9999, 1) AS s(a);

Is it even possible to populate database using postgres functions in Spring? If not, what are my other options. I need like 10k sample records.

According to Spring Boot doc :

Spring Boot can automatically create the schema (DDL scripts) of your DataSource and initialize it (DML scripts) . It loads SQL from the standard root classpath locations: schema.sql and data.sql , respectively.

So if you need to populate data only - just create data.sql file with your sql-scripts, place it to resources folder, then check spring.jpa.hibernate.ddl-auto in the application.properties to be set to none .

If you need more flexible solution, you can use Flyway . To use it - add its dependency to your project

<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
</dependency>

Turn the spring.jpa.hibernate.ddl-auto to validate .

Add spring.flyway.enabled=true to application.properties .

Place you 'migration' sql scripts to the 'default' location resources/db/migration folder. Call them like this, for example:

V1__schema_initialization.sql
V2__data_population.sql

When your spring boot app will be starting, Flyway check your database for missing schema and data then rolls these scripts sequentially.

More info about Flyway is here .

似乎您可以在验证/创建数据库方案之后运行sql脚本。只需将sql查询文件命名为import.sql,而spring应该根据此文档运行它

You need something that will keep a track of what query ran and when ran. Also it should only run once not all the time when application startups.

liquibase is a option which can be used for that.

It will allow DDL as well as DML.

This link will give detail, How can you configure liquibase with spring

https://medium.com/@harittweets/evolving-your-database-using-spring-boot-and-liquibase-844fcd7931da

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