Fixing Intermittent Table Not Found Errors with JUnit when Using Hibernate SchemaExport and H2
Sunday, May 25th, 2008As a part of my test suite, I run a series of tests using Hibernate and the h2 database (h2 seems to be the most lightweight java in memory database around at the moment). These tests run in memory and perform realively quickly, so are a part of my pre-commit build.
In order to move to a spot where the application upgrades work well, I’ve just removed the hbm2ddl.auto create-drop statements from my hibernate.xml file, and wanted to move to a programmatic use of the SchemaExport tool. This was more pain than expected, so I’m documenting what I had to do here.
From the javadoc, and Java Persistence with Hibernate, it looks like you can get away with the following code:
1: Configuration configuration = new Configuration().configure();
2: SchemaExport schemaExport = new SchemaExport(configuration);
3: schemaExport.create(false, true);
Unfortunately I found that this didn’t quite work. It seems that the connection/transactionality/connection pool combination of concerns would cause this kind of code to fail at various degrees. After much gnashing of teeth I ended up with the following code:
1: Configuration configuration = new Configuration().configure();
2: SessionFactory sessionFactory =
configuration.buildSessionFactory();
3: Session session = sessionFactory.openSession();
4: Connection connection = session.connection();
5: SchemaExport schemaExport =
new SchemaExport(configuration, connection);
6: schemaExport.execute(false, true, false, true);
7: session.close();
the critical differences are:
In lines 2-4 we are obtaining a connection to the database which is then used by the schema export tool. In line 6 we do the export using the execute command, passing in a bunch of booleans. This tell it execute command:
- don’t output the sql to the console,
- do execute on the database,
- don’t execute drop statements, and
- do execute create statements.
Finally in line 7, we close the session, ensuring jdbc connection is released and cleaned up. Now any intermittent problems caused by using schema export with h2 database should be avoided.