Over a million developers have joined DZone.
Silver Partner

Spring 3 Makes Use of Embedded Databases Easy

One of the new features introduced in Spring 3 is the support for embedded Java database engines.

· Database Zone

The Database Zone is brought to you in partnership with JetBrains.   Discover how DataGrip provides a UI for operations like creating/modifying tables and managing their columns, keys and indices. 

One of the new features introduced in Spring 3 is the support for embedded Java database engines. Embedded databases like HSQL, H2, or Derby are very useful during the development phase of the project because they are fast, have small memory footprints, improve testability, and are opensource. Using such databases in your development environment eliminates the burden of bigger, bulkier databases like Oracle. If you are using any version of spring prior to version 3, you will configure HSQL databases datasource as shown below

<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource"><property name="driverClassName" value="org.hsqldb.jdbcDriver" /><property name="url" value="jdbc\:hsqldb\:mem\:spring-playground" /><property name="username" value="sa" /><property name="password" value="" /></bean>

and you refer this datasource bean in your entityManagerFactory bean as shown below

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"><property name="dataSource" ref="dataSource" /></bean>

In order to configure an embedded database, we have to take on the pain of remembering the driver class name, url, username or password. Well if you take a look at most of these configurable parameters, they should each be more of a convention than configuration. Using Spring 3 you can eliminate all this pain by simply using the jdbc:embedded-database tag in the spring-jdbc namespace

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"><jdbc:embedded-database id="embeddedDatasource" type="HSQL"/></beans>

A single line of xml configuration shown above creates an instance of embedded HSQL database. The database instance is made available to the Spring container as a bean of type javax.sql.DataSource. This bean can then be injected into data access objects as needed. Spring provides support for HSQL, H2, and Derby natively where HSQL is the default database engine if you don't provide any type. The configuration shown above is useful when you are working with JPA and when you want to create an empty database and to auto-generate database schema i.e. by using hibernate.hbm2ddl.auto property.

Using the jdbc:embedded-database tag you can not only create an empty database but can also create a schema and insert data into it. For example,

<jdbc:embedded-database id="embeddedDataSource"><jdbc:script location="classpath:schema.sql"/><jdbc:script location="classpath:data.sql"/></jdbc:embedded-database>

The above configuration will not only create an instance of embedded HSQL database instance but will also create a schema and will insert data into it. The SQL files specified in the jdbc:script tag should exist in the classpath otherwise you will get a FileNotFoundException.

Creating an embedded database instance programmatically

You can not only create an embedded database instance using xml but you can also create it programmatically by using EmbeddedDatabaseBuilder class fluent API.  This is helpful in scenarios where you need to test your application in a standalone environment without the full-blown Spring application context. It is recommended that your Unit test should be independent of Spring. Lets suppose that you want to unit test UserDao findUserByUsername method, and you want to test it against an embedded database. To do this you will write test code like this

public class UserDaoTest {    private EmbeddedDatabase database;    @Before    public void setUp() throws Exception {        database = new EmbeddedDatabaseBuilder().addDefaultScripts().build();        assertThat(database, is(notNullValue()));    }    @After    public void tearDown() throws Exception {        database.shutdown();    }    @Test    public void shouldFindUserByUsername() {        UserDao dao = new UserDao();        JdbcTemplate jdbcTemplate = new JdbcTemplate(database);        dao.setJdbcTemplate(jdbcTemplate);        User user = dao.findUserByUsername("shekhar");        assertThat(user, is(notNullValue()));    }}

The code shown above will create an embedded database instance of HSQL database and will execute the default scripts to populate the database. The default scripts are named schema.sql which creates the database schema and data.sql which inserts the data into database.

Next time you use embedded database, remember Spring 3 embedded database support.

The Database Zone is brought to you in partnership with JetBrains.   Discover how DataGrip provides a UI for operations like creating/modifying tables and managing their columns, keys and indices. 


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}