java - 通过 Spring data.sql 文件生成示例数据库数据

标签 java spring postgresql spring-boot spring-data

我想用 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-auto 设置为 none

如果您需要更灵活的解决方案,可以使用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/

相关文章:

java - 在 session.close() 之后设置 session=null 是否有意义?

spring - 如何创建 Redis 条件 Bean?

Java等级计算器。我需要一些帮助来开始这个类

Spring从另一个变量设置@value

spring - 在 Pre/Post-Authorize 中获取方法名称

java - Web 服务架构 : Redis (as cache) & PostgreSQL for persistence

sql - 将转储文件上传到 PostgreSQL

postgresql - postgreSQL 9.3 中的动态表名

java - 将文件中的数据导入到从不同类调用的 int 数组中

java - PowerMock 和 Mockito UnfinishedVerificationException