【问题标题】:Spring Boot not running schema.sqlSpring Boot 未运行 schema.sql
【发布时间】:2018-08-26 10:04:00
【问题描述】:

我在运行程序时遇到了运行 schema.sql 的问题。

在我的 pom.xml 中,我已经有了 mysql 配置:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

我只有一门课

@SpringBootApplication
public class Application {...}

在 src/resources 下,我的 schema.sql 包含:

DROP TABLE IF EXISTS test_table;

CREATE TABLE test_table (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    ...
);

在 src/resources 下,我有 application.yml 包含:

spring.datasource.driverClassName: "com.mysql.jdbc.Driver"
spring.datasource.url: "jdbc:mysql://localhost:3306/sample?useSSL=false"
spring.datasource.username: "****"
spring.datasource.password: "****"

我已经确认我能够在启动应用程序时连接到数据库“示例”,但是,它并没有创建表。请指教。

【问题讨论】:

  • application.yml 还是 application.properties?
  • application.yml
  • 但是您在上面放置的格式是属性文件。不是 yml 文件
  • yml 也可以有这种格式,而不仅仅是缩进的格式

标签: mysql spring-boot


【解决方案1】:

那是因为 Spring Boot 有 check in DataSourceInitializer's initSchema() 方法。

只有当你的数据库是H2,DERBY,HSQL类型时它才会执行脚本

但是,您可以通过在 application.properties 中使用以下设置来覆盖此行为

spring.datasource.initialization-mode=always

DataSourceInitializer.java EmbeddedDatabaseConnection.java

【讨论】:

  • 谢谢。这仅适用于嵌入式数据库,不适用于实际数据库。
  • 我正在使用 H2 db,但即使使用这些 application.property 设置,它仍然无法正常工作
  • spring.datasource.initialization-mode 在最新版本的 spring 中被 spring.sql.init.mode 弃用。
【解决方案2】:

在我的情况下(Spring Boot 2.0.0+),只有当属性设置 spring.datasource.initialization-mode=alwaysspring.jpa.hibernate.ddl-auto=none 结合使用时,它才能按预期工作。

【讨论】:

    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 2018-10-03
    • 2021-10-06
    • 2021-03-13
    • 1970-01-01
    • 2020-01-24
    • 2021-09-05
    相关资源
    最近更新 更多