【问题标题】:How to run DDL after Spring auto create db?Spring自动创建数据库后如何运行DDL?
【发布时间】:2020-06-07 19:15:59
【问题描述】:
我的问题很简单。 Spring自动创建模式后如何运行任何DDL语句?
我在 application-test.properties 中设置了以下内容,以从实体 Java 类自动创建数据库架构。
spring.jpa.hibernate.ddl-auto=create-drop
我想在自动创建架构后更改一张表中一列的数据类型。
我尝试在类路径中有一个 schema.sql 文件,但这没有帮助。
请帮忙。
【问题讨论】:
标签:
java
database
spring-boot
hibernate
spring-autoconfiguration
【解决方案1】:
您在脚本中指定的脚本将在创建数据库之前运行。
因此,当您触发 Alter table 命令时,您将得到 Table not found 类型的错误。
我的建议是仅通过 SQL 文件创建数据库并设置
spring.jpa.hibernate.ddl-auto=none 所以系统不会创建自动数据库。
现在要让您的 SQL 文件运行,您可以创建架构并根据平台对其进行初始化。平台值是 spring.datasource.platform。现在您可以创建由 Spring Boot 处理的文件 schema-${platform}.sql 和 data-${platform}.sql。它允许您在必要时选择特定于数据库的脚本。您可以选择数据库(平台)的供应商名称,如 hsqldb、h2、oracle、mysql、postgresql 等。
我已经用 postgres 进行了测试,它对我有用。 Sql 文件名为 schema-postgres.sql
在 application.properties 文件中设置以下属性
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/poc
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=none
spring.datasource.initialization-mode=always