Long story short
I want to generate DB schema from Hibernate mappings and then replace a specific table with a view of the same name before the application starts.
How can I do this using Spring / Hibernate / DbUnit / JDBC or something else?
My problem in details
I have a few integration tests that are executed against an in-memory database.
There's an AView
view in a real database and it's mapped in Java code as
@Entity @Table @Immutable
public class AView {}
I'm generating H2 DB schema from Hibernate mappings for integration tests. And during test application context initialization this view is created as a table. From logs:
Hibernate: drop table AView if exists
Hibernate: create table AView (...)
Some tests fail because of this.
The idea
In order to fix this, I want to make H2 DB schema as similar as possible to the real DB schema. First, I want to generate DB schema from Hibernate mappings, and then replace AView
table with AView
view.
What I have tried
I have found a similar question: How to execute sql script after db schema generation but before application startup
I created a file schema.sql with DROP TABLE / CREATE VIEW
statements. I tried to put the file in src/test/resources/schema.sql but it's not picked up automatically by Spring. I tried to specify this file explicitly in @Sql
annotation, but it still doesn't have a visible effect.
I execute the tests via IntelliJ IDEA (if this is important).
My Code
Test and Test application context:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestH2Config.class })
@TransactionConfiguration(defaultRollback = true)
@Transactional
public class AViewServiceIT {}
@Configuration
@PropertySource({"classpath:datasource-h2.properties"})
@EnableTransactionManagement
//@Sql({"/schema.sql"})
public class TestH2Config {}
datasource-h2.properties
datasource.driverClassName=org.h2.Driver
datasource.url=jdbc:h2:mem:itest;MODE=MSSQLServer;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS itest\\;SET SCHEMA itest
datasource.username=sa
datasource.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
Spring framework version is 4.1.9.RELEASE.