Wednesday, August 21, 2013

Working with H2 database

 H2 is Java SQL database. It helps during development and testing of Java/JEE applications. It can act as in-momory database or as storing physically. The following are main features of this database:
  • Very fast, open source, JDBC API
  • Embedded and server modes; in-memory databases
  • Browser based Console application
  • Small footprint: around 1.5 MB jar file size
How to use in my Java/JEE app?

Define following dependency in the pom.xml
 Define the datasource bean definition:

<bean id="jpaDataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.h2.Driver" />
      <property name="url" value="jdbc:h2:~/foo_db;DB_CLOSE_DELAY=-1" />
</bean>



Use the following hibernate dialect(if your app is using hibernate as entity manager)

org.hibernate.dialect.H2Dialect

You are all set to use this database.

Where the database files are stored?

When using database URLs like jdbc:h2:~/test, the database is stored in the user directory. For Windows, this is usually C:\Documents and Settings\<userName> or C:\Users\<userName>. If the base directory is not set (as in jdbc:h2:test), the database files are stored in the directory where the application is started (the current working directory). When using the H2 Console application from the start menu, this is <Installation Directory>/bin. The base directory can be set in the database URL. A fixed or relative path can be used. When using the URL jdbc:h2:file:data/sample, the database is stored in the directory data (relative to the current working directory). The directory is created automatically if it does not yet exist. It is also possible to use the fully qualified directory name (and for Windows, drive name). Example: jdbc:h2:file:C:/data/test

1 comment:

  1. Thank for the tips. Database files can be stored in arbitrary - dynamically constructed path as in the example given on http://www.jvmhost.com/spring-hosting

    ReplyDelete