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

Đor*_*ulj 22 java spring hibernate spring-boot

当我使用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
Run Code Online (Sandbox Code Playgroud)

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

Evg*_*rov 23

这里查看文件.

在基于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.
Run Code Online (Sandbox Code Playgroud)

默认值是embedded- 例如,只有在运行时才初始化,而像H2一样运行嵌入式数据库.

还看到斯蒂芬的答案在这里.他说:

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

所以尝试设置:

spring.datasource.initialization-mode=always
Run Code Online (Sandbox Code Playgroud)

  • 它在Spring 2.0之前工作,我不知道为什么它不再存在,但我也在寻找答案.我只需要在`schema.sql`中为`h2`创建一个模式,因为我已升级到2.0它停止工作. (4认同)
  • @11thdimension 看起来新的主要 Spring Boot 版本不支持它。很高兴我们可以在文档中找到它。 (2认同)

Pan*_*kos 18

最近更新

从 Spring Boot 2.7 版本开始

该财产spring.datasource.initialization-mode已被删除。

您应该从这个版本开始使用替换属性spring.sql.init.mode

例子:spring.sql.init.mode:always

Spring Boot 2.7 变更日志


acd*_*ior 13

未嵌入(例如MySQL)

如果加载未嵌入的数据库,则在Spring Boot 2中需要添加:

spring.datasource.initialization-mode=always
Run Code Online (Sandbox Code Playgroud)

查看迁移指南:

数据库初始化

现在,只对嵌入式数据源启用基本DataSource初始化,并在使用生产数据库时立即关闭.新的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 {
Run Code Online (Sandbox Code Playgroud)

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

@RunWith(SpringRunner.class)
@DataJpaTest                       // works
@ActiveProfiles("sep-test")
public class MyEntityRepositoryTest {
Run Code Online (Sandbox Code Playgroud)

要么

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