首页 > 解决方案 > Spring Boot 启动时无法执行 data.sql 和 schema.sql

问题描述


我正在尝试针对在容器中运行的 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 属性吗?

标签: springspring-boot

解决方案


您可以使用以下属性更新 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设置为任何值validateupdatecreatecreate-drop。Spring boot 生成模式脚本并根据应用程序中可用的实体创建表。

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

您还可以根据平台运行脚本。假设您要运行hsqldb数据库的脚本,然后在 application.properties 文件中设置spring.datasource.platform=hsqldb并在资源文件夹下创建脚本文件schema-hsqldb.sqldata-hsqldb.sql 。您可以找到有关如何使用 spring boot 在启动时加载 schema.sql 和 data.sql 的更多详细信息。


推荐阅读