13.8 Embedded database support

The org.springframework.jdbc.datasource.embedded package provides support for embedded Java database engines. Support for HSQL and H2 is provided natively. There is also an extensible API for plugging in new embedded database types and DataSource implementations.

13.8.1 Why use a embedded database?

An embedded database is useful during the development phase of a project due to its lightweight nature. Ease of configuration, quick startup time, testability, and the ability to rapidly evolve SQL during development are just some of the benefits of using an embedded database.

13.8.2 Creating an embedded database instance using Spring XML

When you wish to expose an embedded database instance as a bean in a Spring ApplicationContext, use the embedded-database tag in the spring-jdbc namespace:

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

The configuration above creates an embedded HSQL database populated with SQL from schema.sql and testdata.sql resources in the classpath. 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.

13.8.3  Creating an embedded database instance programatically

The EmbeddedDatabaseBuilder class provides a fluent API for constructing an embedded database programmatically. Use this when you need to create an embedded database instance in a standalone environment, such as a data access object unit test:

    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    EmbeddedDatabase db = builder.type(H2).script("schema.sql").script("test-data.sql").build();
    // do stuff against the db (EmbeddedDatabase extends javax.sql.DataSource)
    db.shutdown()
  			

13.8.4 Extending the embedded database support

Spring Jdbc's embedded database support can be extended in two ways:

  1. Implement EmbeddedDatabaseConfigurer to support a new embedded database type, such as Apache Derby.

  2. Implement DataSourceFactory to support a new DataSource implementation, such as a connection pool, to manage embedded database connections.

You are encouraged to contribute back extensions to the Spring community at jira.springframework.org.