我正在尝试在我的 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}"
注释的属性,并且该值确实被正确填充)。
作为替代方案,我可以使用运行脚本的@Sql("classpath:data-h2.sql")
注释测试类 - 但是它对每个测试都这样做,而我希望脚本在任何测试执行之前运行一次。
我还尝试删除它并使用空白schema.sql
并将人口移动到data.sql
(如此处建议),但 Spring 会抱怨空的模式文件 - 这对我来说毫无用处,因为我的模式是自动生成的,我当然不想重新创建它(注意:如果没记错的话,可能与休眠属性冲突)。
我已经浏览了这里的一些答案,但我唯一可以使用的答案不起作用。
我能看到的唯一解决方案是保留@Sql
注释,但尝试在每次测试后清除表,并使用另一个@Sql
注释在@After
上启动另一个脚本。
这对我来说似乎很疯狂——必须有更好的解决方案。
我是否错过了比我的配置中更深奥的东西?
只需将您的文件放在/main/resources 目录中(您已经执行的操作)
弹簧启动 2:
正确的属性是:
spring.datasource.initialization-mode=always
在 Spring 引导文档中阅读有关此主题的更多信息:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc
弹簧靴 1
您只需将数据 h2.sql 放在类路径中
在 Spring 引导文档中阅读有关此主题的更多信息: https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc