为什么 Spring Boot 2.0 应用程序不运行 schema.sql?

新手上路,请多包涵

当我使用 Spring Boot 1.5 时,在应用程序启动时,当设置了适当的配置时,Hibernate 会执行位于 /resources 文件夹中的 schema.sql 文件。在 Spring Boot 2.0 发布后,此功能不再起作用。我在文档中找不到有关此更改的任何信息。这是我的 application.properties 文件内容:

 spring.datasource.url=...
spring.datasource.username=...
spring.datasource.password=...

#spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

Spring Boot 2.0 是否有一些变化或者这是一个错误/问题?

原文由 Đorđe Pržulj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 919
2 个回答

此处 查看文档。

在基于 JPA 的应用程序中,您可以选择让 Hibernate 创建架构或使用 schema.sql,但您不能同时执行这两项操作。如果您使用 schema.sql,请确保禁用 spring.jpa.hibernate.ddl-auto。

你有 spring.jpa.hibernate.ddl-auto=create-drop 这就是为什么 schema.sql 没有被执行。看起来这就是 Spring Boot 的工作方式。

编辑

我认为问题(不是真正的问题)是您的应用程序指向一个 mysql 实例。

查看 当前的 Spring Boot 属性

 spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts.

默认值为 embedded 例如,仅当您正在运行和嵌入数据库(如 H2)时才初始化。

另请参阅 此处 斯蒂芬的回答。他说:

将 spring.datasource.initialization-mode=always 添加到您的项目中就足够了。

所以尝试设置:

 spring.datasource.initialization-mode=always

原文由 Evgeni Dimitrov 发布,翻译遵循 CC BY-SA 3.0 许可协议

非嵌入式(例如 MySQL)

如果你加载一个 非嵌入式 的数据库,在 Spring Boot 2 中你需要添加:

 spring.datasource.initialization-mode=always

查看 迁移指南

数据库初始化

基本数据源初始化现在仅对嵌入式数据源启用,并且在您使用生产数据库时将立即关闭。新的 spring.datasource.initialization-mode (替换 spring.datasource.initialize )提供更多控制。


嵌入式(例如 h2)

我曾经遇到过类似的问题,即使它是一个 h2(所以它 一个嵌入式数据库),我的 h2 配置是由 my-test 配置文件激活的。

我的测试课是这样的:

 @RunWith(SpringRunner.class)
@SpringBootTest                     // does not work alone
@ActiveProfiles("my-test")
public class MyEntityRepositoryTest {

问题是 @SpringBootTest 单独 没有初始化测试数据库。我不得不使用 @DataJpaTest@SpringBootTest + @AutoConfigureTestDatabase 。例子

@RunWith(SpringRunner.class)
@DataJpaTest                       // works
@ActiveProfiles("sep-test")
public class MyEntityRepositoryTest {

或者

@RunWith(SpringRunner.class)
@SpringBootTest                     // these two
@AutoConfigureTestDatabase          // together work
@ActiveProfiles("sep-test")
public class MyEntityRepositoryTest {

原文由 acdcjunior 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题