Saturday, August 18, 2012

H2 In-memory database

In-memory databases  are the databases which reside in main memory.These databases either partially or fully lack the durability property of ACID (atomicity, consistency,isolation and durability).
In-memory databases are used when either we want very quick performance  or in the cases where data used in application does not need to be durable. While developing the testcases of DAO layer, in memory database in embedded mode is preferred.  This provide quick access and full control of databases in the test.
In the arena of in-memory databases H2 has it significant presence.It can be included in the application using maven dependency and can be run in imbedded or standalone mode.
Maven Dependency
Bean configuration to start and stop the H2 database along with spring bean factory creation and destroy
<bean id = ""
    <constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,8043" />
H2 default connection details
driver - org.h2.Driver
Hibernate Dialect -org.hibernate.dialect.H2Dialect
jdbc url -jdbc:h2:~/test
user name - sa
password -
Starting server from command line-

java -cp h2-1.3.167.jar
Shutting down server from command line –

java -cp h2-1.3.167.jar -tcpShutdown tcp://localhost:909

Basic setup to use H2 in unit testing -
To use H2 in unit test cases, we might want to extend H2DBEnabledTestCase class, which starts the H2 server in setup method  so that during test run database could be available and stops server in tearDown method.

import java.sql.SQLException;
import junit.framework.TestCase;

public abstract class H2DBEnabledTestCase extends TestCase {

 private Server httpServer;

 protected void setUp() throws SQLException {
  httpServer = Server.createTcpServer(
    new String[] { "-tcpPort", "8080", "-tcpAllowOthers" }).start();

 protected void tearDown() {
  if (httpServer != null && httpServer.isRunning(false)) {
H2 In-memory - The complete in-memory usage, keeps the complete database in main memory.  As soon as the database is shut down all the data gets lost.To use database in this way we neither need to explicitly start not stop it. Database will automatically become available as soon as you try to access it with specific URL.
In-memory jdbc url - jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
Using the database in embedded mode Sample-
While including H2 in our application, we implemented facade for performing H2 related interactions and operations.

Sample use of H2 using above mentioned facade

Running application of above code can be downloaded from here . You will need java 6.0 and maven 3 to get the application running.

Kindly follow below mentioned steps to see it in execution –
  1. Download the application and extract it.
  2. Execute mvn eclipse:eclipse by traversing to the location of pom.xml
  3. Import the application in eclipse
  4. Run  as Junit test.