跨多个架构的H2数据库单元测试 [英] h2 database unit test across multiple schema

查看:113
本文介绍了跨多个架构的H2数据库单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将单元测试与h2数据库一起使用。我的应用程序使用MSSQL数据库。下面是我的应用程序中正在使用的2个表:

  SchemaA.dbo.Table1< 
SchemaB.dbo.table2<

@ Entity< br>
@Table(name = SchemaB..table)< br>
A类< br>
{

私人长id;

............

}

我正在尝试编写单元测试来测试上述类的持久性。但是h2数据库无法识别此表名语法:



SchemaB..table



注意:两个点之间模式名称和表名称。



任何建议将不胜感激。

解决方案

您可能想使用Table JPA批注的schema属性。
例如:

  @Entity(name = Foo)
@Table(name = TABLE_FOO,schema = bar)

如果您有单个数据源,它将连接到您的h2与用户A。为了访问架构 bar,您可能要告诉h2在连接上自动创建架构 bar。

  jdbc:h2:mem:play; MODE = MySQL; INIT = RUNSCRIPT FROM'test / init.sql'

JDBC URL test / init.sql的最后部分指向具有以下内容的sql文件。

 如果不存在则创建模式bar 

H2将执行sql并在connect上创建模式。 / p>




我在 github



该项目有一个init.sql文件,该文件创建2个架构,foo和bar。



2个模型类foo.A和bar.B使用@Entity(schema = foo,name = A)来相应地指定架构。



测试用例使用播放框架,因此每次执行测试用例时都可以使用内置的演变工具。但是在执行测试用例之前,最好使用setUp方法应用自己的sql脚本。请参阅测试文件夹中的示例测试用例。 (实际上是scalaTest,但基本上与junit具有相同的概念)


I am trying to use unit test along with h2 database. My application uses MSSQL database. And below are the 2 table that am using in my application:

SchemaA.dbo.Table1<br>
SchemaB.dbo.table2<br>

@Entity<br>
@Table(name="SchemaB..table")<br>
Class A <br>
{

  private Long id;

  ............

}

I am trying to write unit test to test the persistance of the above class. But h2 database does not recognise this tablename syntax:

SchemaB..table

Note : the 2 dots between schema name and table name.

Any suggestion would be greatly appreciated.

解决方案

You may want to use the schema attribute of the Table JPA annotation. For example:

@Entity(name = "Foo")
@Table(name = "TABLE_FOO", schema = "bar")

If you have a single data source, which connects to your h2 with user A. In order to access schema 'bar', you may want to tell h2 to automatically create schema 'bar' on connect.

jdbc:h2:mem:play;MODE=MySQL;INIT=RUNSCRIPT FROM 'test/init.sql'

The final part of the JDBC URL test/init.sql points to a sql file with the following content.

CREATE SCHEMA IF NOT EXISTS bar

H2 will execute the sql and create the schema on connect.


I've created a demo project at github.

The project has an init.sql file that creates 2 schema, foo and bar.

2 model classes foo.A and bar.B that use @Entity(schema="foo", name="A") to specify schema accordingly. see app/models.

The test case uses play framework therefore the built-in evolution tool can be applied every time test cases are executed. But it should be fine to use setUp method to apply your own sql script before executing test cases. Please see test folder for the sample test case. (it's actually scalaTest but it basically has the same idea as junit)

这篇关于跨多个架构的H2数据库单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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