我想用 data.sql 文件初始化我的 postgres 数据库。我创建了如下查询:
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);
是否可以在 Spring 中使用 postgres 函数填充数据库?如果没有,我的其他选择是什么。我需要大约 10k 条样本记录。
最佳答案
根据 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.
因此,如果您只需要填充数据 - 只需使用您的 sql 脚本创建 data.sql
文件,将其放入 resources
文件夹,然后检查 spring
设置为 application.properties
中的 .jpa.hibernate.ddl-autonone
。
如果您需要更灵活的解决方案,可以使用Flyway .要使用它 - 将其依赖项添加到您的项目中
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
将spring.jpa.hibernate.ddl-auto
设置为validate
。
将 spring.flyway.enabled=true
添加到 application.properties
。
将“迁移”sql 脚本放置到“默认”位置 resources/db/migration
文件夹。像这样称呼他们,例如:
V1__schema_initialization.sql
V2__data_population.sql
当您的 spring boot 应用程序启动时,Flyway 会检查您的数据库是否缺少架构和数据,然后按顺序滚动这些脚本。
有关 Flyway 的更多信息是 here .
关于java - 通过 Spring data.sql 文件生成示例数据库数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49747120/