Friday, 18 May 2007

JPA Maven 2 Hibernate HSQL Test Database.

whatadorkiam posted exactly the article I wanted but it did not work with JPA. After some messing about I got it to work so here is HowTo set up your Maven 2 JPA Hibernate projects so your unit tests run on the test (in-memory) HSQL Database.

Why is this a good idea? Because your test database is always rebuilt for your unit tests but your configured hibernate connection for you installation is left alone. You can build the project and run all tests without installing a database server.


cat src/main/resources/META-INF/persistence.xml
<persistence>
<persistence-unit name="MyPersistence">
<description>MySQL Database<description>
<properties>
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver">
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost/myDataBase" />
<property name="hibernate.connection.username"
value="myuser" />
<property name="hibernate.connection.password"
value="mypass" />
<property name="hibernate.hbm2ddl.auto"
value="update" />
</properties>
</persistence-unit>
</persistence>


cat src/test/resources/META-INF/persistence.xml
<persistence>
<persistence-unit name="MyPersistence">
<description>HSQL Temp Test Database<description>
<!--
This is not good but the only way I got JPA Annotations
to work. YOu have to list your Entity Classes. :-/
-->
<class>my.package.model.entities.AddressEntity</class>
<class>my.package.model.entities.PersonEntity</class>
<class>my.package.model.entities.XyzEntity</class>
...
<properties>
<property name="hibernate.connection.driver_class"
value="org.hsqldb.jdbcDriver" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.connection.url"
value="jdbc:hsqldb:mem:MyDataBase" />
<property name="hibernate.connection.username"
value="sa" />
<property name="hibernate.connection.password"
value="" />
<property name="hibernate.hbm2ddl.auto"
value="update" />
</properties>
</persistence-unit>
</persistence>


cat pom.xml
...
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5 </version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.7</version>
<scope>test</scope>
</dependency>
...