Unit testing JPA - Hibernate components with in-memory H2 database
Skip to end of metadata
Go to start of metadata

The goal

Be able to unit test database related components without the need to set up and entire RDBMS ecosystem. Enabling integration tests to be run by a continuous integration server.

The solution

Create a database on the fly, in-memory. This is achieved by using Maven, Springframework and Hibernate together.


I have tested with Derby (former Cloudscape). Derby provides an EmbeddedDriver. However files are still created in the filesystem.

HSQLDB should be able to do the trick but I was not able to get the configuration right due to a lack of proper documentation.

H2 delivered the final solution. I added the following dependency to my pom.xml:

Test class

Personally I am a big fan of TestNG. Mainly for the ability to group tests. Spring 2.5.x now has excellent annotation based support for TestNG.

If you your boss or your customer requires you to use JUnit then you can subclass AbstractTransactionalJUnit4SpringContextTests instead.

After the main application-context.xml is loaded I load test-application-context.xml which overrides a couple of bean definitions.

Test application context

Initialize database schema

Hibernate has the ability to create a database schema on the fly the first time the SessionFactory is loaded. This is configured in two places. First the HibernateJpaVendorAdapter needs to be told to generateDdl. Second in the file META_INF/persistence.xml (the default JPA persistence context definition) I set the hibernate.hbm2ddl.auto to create.

To fill the database with initial data add a file called import.sql containing insert statements to the classpath. To get a grasp of what hbm2ddl is doing we need to add the following logging configuration:


  • No labels