【问题标题】:spring.datasource.data picked up, but script never executedspring.datasource.data 拾取,但脚本从未执行
【发布时间】:2020-04-22 14:45:33
【问题描述】:

我正在尝试在我的 Spring 引导应用程序中为测试类设置内存 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}" -annotated 属性,并且该值确实被正确填充)。

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

我还尝试删除它并使用空白 schema.sql 并将人口移动到 data.sql(建议 here),但 Spring 会抱怨空架构文件 - 这对我来说没用,因为我的架构是自动生成的,我当然不想重新创建它(注意:如果有记忆,可能与休眠属性发生冲突)。

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

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

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

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

【问题讨论】:

  • 旁注:ddl-auto 属性不应该配置在spring.jpa.hibernate 下而不是spring.hibernate 下吗?
  • @michalk 看起来你是对的 - 感谢您指出这一点

标签: java spring-boot integration-testing h2


【解决方案1】:

只需将你的文件放在 /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

【讨论】:

  • 不幸的是文件那里,从我的配置中你可以看到,属性也在那里!但是没有。
  • 详细说明我上面的评论:“nope”表示在文件到​​位和配置中设置属性的情况下不执行任何脚本。我的 Spring Boot 版本是 1.5.8.RELEASE,这是否相关...
  • 是的,这已从 1 更改为 2。我已将 Spring Boot 1 添加到我的答案中
  • 抱歉回复晚了。 1) 看起来如此(没有日志,属性被填充) 2) 谢谢你 - 但无论文件在哪里,它显然仍然对我不起作用......
  • 也许你应该尝试创建一个最小的例子。如果这能与您的项目进行比较
猜你喜欢
  • 1970-01-01
  • 2021-11-07
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多