How to add embedded database support to spring xml based configuration

Take following steps to add embedded database support in Spring. This is required to have local in memory database for integration testing and/or local development.

Add Jar using Maven or Gradle

Add latest version of h2 database.

POM.XML
 <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>1.3.160</version>
</dependency> 

Add H2 as datasource

Update Spring configuration file.

spring-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd">
	<jdbc:embedded-database id="dataSource" type="H2">
	<jdbc:script location="classpath:schema.sql"/>
	<jdbc:script location="classpath:mock-data.sql"/>
	</jdbc:embedded-database>
</beans>

Add database initialization scripts

Initialize database by adding mock-data.sql. Assumption is that you already have schema.sql which contains all the database scripts.

Java6 comes with JavaDB which can also be used as embedded database. JavaDB is a fully transactional, secure, standards-based database server, written entirely in Java, and fully supports SQL, JDBC API, and Java EE technology. JavaDB .

Version History


Date Description
2015-02-26    Initial Version