【问题标题】:Unable to execute data.sql and schema.sql at Spring Boot StartupSpring Boot 启动时无法执行 data.sql 和 schema.sql
【发布时间】:2018-11-28 15:19:47
【问题描述】:


我正在尝试针对在容器中运行的 MySQL 数据库为 Spring Boot 应用程序执行一些数据库初始化。 在身份验证过程中,我收到错误“找不到表”。我检查了数据库,确实没有创建任何表。 数据库属性中是否缺少某些内容?

spring.datasource.url = jdbc:mysql://172.17.0.2:3306/schema
spring.datasource.username = user
spring.datasource.password = password
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.data.rest.basePath=/
spring.datasource.data = classpath:/data.sql
spring.datasource.schema = classpath:/schema.sql

总而言之,只要我从 mysql 命令行创建 DDL,JDBC 设置就可以正常工作。所以它只是在启动时不执行 data.sql 和 schema.sql。 我需要一些额外的 mysql 属性吗?

【问题讨论】:

  • 你定义你的spring.datasource.driverclassname了吗?
  • 你在用spring-data吗?
  • 我刚刚尝试添加驱动程序类名,但没有改变。我也在使用“spring-boot-starter-data-jpa”。有区别吗?
  • 您确定您提供了正确的 sql 文件路径吗?也许您可以尝试将您的 sql 文件添加到资源文件夹中并删除 spring.datasource.data = classpath:/data.sql spring.datasource.schema = classpath:/schema.sql
  • @Carla - 你能解决这个问题吗?

标签: spring spring-boot


【解决方案1】:

您可以使用以下属性更新 application.properties。

application.properties:

spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=false
spring.datasource.initialization-mode=always

spring.jpa.generate-ddl 的默认值为 false。如果您将 spring.jpa.generate-ddl=truespring.jpa.hibernate.ddl-auto 设置为任何值 validate,更新、创建创建删除。 Spring boot 生成模式脚本并根据应用程序中可用的实体创建表。

现在您应该在资源文件夹下创建 schema.sqldata.sql 文件并设置属性 spring.datasource.initialization-mode=always 在 application.properties 中。

您还可以根据平台运行脚本。假设您要运行 hsqldb 数据库的脚本,然后在 application.properties 文件中设置 spring.datasource.platform=hsqldb 并创建脚本文件 schema-hsqldb .sqldata-hsqldb.sql 在资源文件夹下。 您可以找到有关how to load schema.sql and data.sql on startup with spring boot 的更多详细信息。

【讨论】:

【解决方案2】:

如你所愿

spring.jpa.hibernate.ddl-auto = create-drop

Spring 不运行 schema.sql 和 data.sql。

试试看

spring.jpa.hibernate.ddl-auto = none

查看docs

在基于 JPA 的应用程序中,您可以选择让 Hibernate 创建模式或使用 schema.sql,但不能同时使用这两种方法。如果您使用 schema.sql,请确保禁用 spring.jpa.hibernate.ddl-auto。

【讨论】:

  • 谢谢,我已尝试更改为“无”,但仍然不执行 SQL 文件。
【解决方案3】:

在 spring-boot 更新 pom 文件之前,一切都按预期工作

<version>1.5.8.RELEASE</version>

<version>2.3.3.RELEASE</version>

切换回和更新所有测试均通过,无任何异常。在版本 2.3.3 中,由于数据库中缺少数据而导致测试错误。 我花了几个小时解决 Spring 版本 2.3.3.RELEASE 的 ddl 初始化,但没有找到常规解决方案。

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2016-10-13
    • 2022-10-05
    • 2015-03-11
    • 1970-01-01
    • 2020-09-29
    • 2018-08-26
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多