Unit Testing of DB Schema and Named Queries

It is essential to software development, that bugs or misconfiguration are detected as early as possible. Therefore, tests being run during the build process can help to detect problems before your software is applied in a productive environment. In a EJB 3.0 application you may validate your DB-Schema and your named queries in a unit test, by starting up the EntityManagerFactory. It is one of the fine new features of JPA 1.0 (related to CMP in EJB 2.x) that you are able to use it without a container in a normal Java application. For your test you need a jndi.properties in your classpath:


In addition a persistence.xml containing references to all entity classes has to be placed in META-INF:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	<persistence-unit name="MYAPP_DB">
		<!-- more class mappings -->
			<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:myapp-db-test" />
			<property name="hibernate.connection.username" value="sa" />
			<property name="hibernate.connection.password" value="" />
			<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
			<property name="hibernate.hbm2ddl.auto" value="create-drop" />

The class definitions have to be placed in the persistence configuration, if you use maven for example, since the entity auto-detection considers the class path entry being host by the persistence unit, only. In a Maven build (life cycle phase integration-test), this is target/test-classes. The entities generally are not situated in the test-classes folder.

Last but not least a test class which starts up the entity manager is given in the next listing:

public class MappingTest {
	public void testMapping() {
		EntityManagerFactory factory = Persistence

All these files are by convention situated in src/test/java and src/test/resources. Your pom.xml should contain the dependency to the used testing framework (like jUnit or TestNG), the hibernate entity-manager, hibernate annotations and hsqldb. For dependencies which are necessary only for the test (like hsqldb) the scope should be set to test in order not to pollute your dependency tree with unnecessary artifacts.

Leave a Reply

Your email address will not be published. Required fields are marked *