gpt4 book ai didi

java - spring.datasource.data 已获取,但脚本从未执行

转载 作者:行者123 更新时间:2023-12-01 17:16:53 31 4
gpt4 key购买 nike

我正在尝试在 Spring boot 应用程序中为测试类设置内存中的 H2 表。

我的配置看起来像:

spring:
jpa:
show-sql: true
generate-ddl: true
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
datasource:

# not sure which one to use so added both just in case
initialization-mode: always
initialize: true

platform: h2

# casting a wide net here, but no cookie - completely ignored
data: data-h2.sql,classpath*:data-h2.sql, classpath:data-h2.sql

url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
driver-class-name: org.h2.Driver
username: sa
password:

如您所见,我正在尝试加载 data-h2.sql数据库初始化时的脚本。

不幸的是,无论值如何,该属性都会被忽略。

我确定配置文件已正确获取(例如,除其他外,我拼命在我的测试类中添加了 @Value("${spring.datasource.data}" 带注释的属性,并且该值确实已正确填充)。

作为替代方案,我可以用 @Sql("classpath:data-h2.sql") 注释测试类它确实运行了脚本 - 但是它对每个测试都这样做,而我希望脚本在任何测试执行之前运行一次。

我还尝试删除它并使用空白 schema.sql并将人口移至data.sql (如建议的 here ),但是 Spring 会提示空模式文件 - 这对我来说毫无用处,因为我的模式是自动生成的,我当然不想重新创建它(注意:可能与如果没记错的话,是一个 hibernate 属性)。

我浏览了一些答案 here ,但唯一的one我可以使用,但不起作用。

我能看到的唯一解决方案是保留 @Sql注释,但尝试在每次测试后使用另一个 @Sql 清除表格注释在 @After 上启动另一个脚本。

这对我来说似乎很疯狂 - 必须有更好的解决方案。

我是否遗漏了一些比我的配置中已有的更深奥的东西?

最佳答案

只需将文件放在/main/resources 目录中(您已经做了)

Spring Boot 2:

正确的属性是:

spring.datasource.initialization-mode=always

在 Spring Boot 文档中了解有关此主题的更多信息:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc

Spring Boot 1

您只需将 data-h2.sql 放在类路径中

在 Spring Boot 文档中阅读有关此主题的更多信息: https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc

关于java - spring.datasource.data 已获取,但脚本从未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61367995/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com