春季靴. @DataJpaTest H2嵌入式数据库创建架构 [英] Spring Boot. @DataJpaTest H2 embedded database create schema

查看:138
本文介绍了春季靴. @DataJpaTest H2嵌入式数据库创建架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据层中有几个实体以特定的架构存储.例如:

I have couple of entities in my data layer stored in particular schema. For example:

@Entity
@Table(name = "FOO", schema = "DUMMY")
public class Foo {}

我正在尝试设置H2嵌入式数据库,以对我的数据层进行集成测试. 我在测试中使用@DataJpaTest批注以自动配置H2嵌入式数据库.但是,表的创建失败,因为在数据库初始化时未创建架构DUMMY.

I'm trying to setup H2 embedded database for integration testing of my data layer. I'm using @DataJpaTest annotation for my tests to get H2 embedded database configured automatically. However, the creation of tables fails because schema DUMMY is not created at DB initialization.

关于在测试用例中创建表之前如何创建架构的任何想法?

Any ideas on how to create schema before creation of tables in test cases?

我尝试使用@Sql(statements =如果不存在假的话则创建模式"),但没有成功.

I've tried to use @Sql(statements="CREATE SCHEMA IF NOT EXISTS DUMMY") but didn't succeed.

此外,我还尝试在test.properties文件中将spring.datasource.url = jdbc:h2:mem:test;INIT=CREATE SCHEMA IF NOT EXISTS DUMMY设置为与TestPropertySource("classpath:test.properties")一起设置,但是那也不起作用.

Also, I've tried to set spring.datasource.url = jdbc:h2:mem:test;INIT=CREATE SCHEMA IF NOT EXISTS DUMMY in my test.properties file together with TestPropertySource("classpath:test.properties"), but that didn't work too.

推荐答案

我遇到了同样的问题,我设法通过在内容文件夹中创建schema.sql(在资源文件夹中)来解决

I had the same issue, I managed to resolve by creating schema.sql (in resources folder) with the content

CREATE SCHEMA IF NOT EXISTS <yourschema>

可以找到文档

Documentation can be found here but imho the lack of real examples make it very complex. Warning: this script is also executed within the normal (not test) environment.

不是强制性的,而是一种好的做法,仅在测试范围内添加h2依赖项

Not mandatory, but good practice, add h2 dependency only in test scope

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>test</scope>
</dependency>

这篇关于春季靴. @DataJpaTest H2嵌入式数据库创建架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆