indiWiz.com

Subhash's Tech Log

Archive for the ‘hibernate’ tag

Unit Testing Hibernate Code With Derby

with 5 comments

We faced a scenario which I have faced before: our application uses Hibernate and Oracle Database. And every time we run tests, we had to configure the database specific to that system. I was fed up by this, and explored the possibility of running our code against a test DB. We finalized on Derby.

So the next step was configuring hibernate.cfg.xml. We did this:

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
        <property name="hibernate.connection.url">jdbc:derby:target/testdb;create=true</property>
        <property name="show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
        <property name="hbm2ddl.auto">create-drop</property>
    </session-factory>
</hibernate-configuration>

In the hibernate.connection.url property note the parameter create=true. This ensures when the JDBC layer establishes the connection, the Database will be created if it has not been created earlier. Another important parameter from testing perspective is: hbm2ddl.auto. The value set in this parameter is create-drop. This ensures if the tables that are mapped in *.hbm.xml files are not present in the Database, they will be created (during the creation of SessionFactory). And when the SessionFactory is closed, the tables will be dropped. Perfect for testing! Note that, if you want the database tables to persist, just give create instead of create-drop.

So where will the DB be created? This is specified in the hibernate.connection.url property. Note the string target/testdb. This is the folder where the DB will be created. Ensure that the relative folder target/ exists in this case (testdb will be automatically created because of the property create=true).

In some scenarios we might want to test the correctness of the application by manually verifying the database content. In such situation, as discussed previously, change the hbm2ddl.auto property to create. After that connect to that DB using the Derby command-line tool:

$ java -cp $JAVA_HOME/db/lib/derby.jar:$JAVA_HOME/db/lib/derbytools.jar \
   org.apache.derby.tools.ij

This will open the ij prompt. Connect to our DB using it:

ij> connect 'jdbc:derby:target/testdb';
ij> select * from __table__;

Isn’t it cool?

Written by Subhash Chandran

January 5th, 2009 at 8:10 pm

Posted in Java

Tagged with , ,