h2 database unit test across multiple schema

时光毁灭记忆、已成空白 提交于 2019-12-08 08:26:54

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/23305778/h2-database-unit-test-across-multiple-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!