Spring Download. @DataJpaTest H2 built-in database creates schema

I have several objects at my data level stored in a particular schema. For instance:

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

I am trying to configure an embedded H2 database to test the integration of my data layer. I use the @DataJpaTest annotation for my tests to automatically configure the embedded H2 database. However, tables are not created because the DUMMY schema DUMMY not created during DB initialization.

Any ideas on how to create a schema before creating tables in test cases?

I tried using @Sql (statements = "CREATE SCHEMA IF NOT EXISTS DUMMY") but failed.

In addition, I tried to set spring.datasource.url = jdbc:h2:mem:test;INIT=CREATE SCHEMA IF NOT EXISTS DUMMY in my test.properties file along with TestPropertySource("classpath:test.properties") , but that too did not work.

+6
source share
2 answers

I had the same problem, I was able to solve by creating schema.sql (in the resources folder) with the contents

CREATE SCHEMA IF NOT EXISTS <yourschema>

The documentation can be found here , but imho the lack of real examples makes it very complex. Warning: this script also runs in a normal (non-test) environment.

Not necessarily, but good practice, add h2 dependency only in validation area

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

After several hours of struggle, I found a workaround.

You can define spring.jpa.properties.hibernate.default_schema = DUMMY in application.properties .

And then set spring.jpa.properties.hibernate.default_schema = to test.properties and use with @TestPropertySource("classpath:test.properties")

Thus, the DUMMY schema will not be created and entities will be created by default.

+1
source

All Articles