DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Camel Route - Unit Testing
  • Spring Boot - Unit Test your project architecture with ArchUnit
  • Data Structures and Indexing for Operations on Deeply Nested Comments
  • Top 10 Advanced Java and Spring Boot Courses for Full-Stack Java Developers

Trending

  • Debugging Tips and Tricks: A Comprehensive Guide
  • Unveiling Vulnerabilities via Generative AI
  • TDD With FastAPI Is Easy
  • Multi-Tenancy With Keycloak, Angular, and SpringBoot
  1. DZone
  2. Data Engineering
  3. Databases
  4. Spring 3 Makes Use of Embedded Databases Easy

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.

Shekhar Gulati user avatar by
Shekhar Gulati
·
Sep. 27, 10 · News
Like (0)
Save
Tweet
Share
116.08K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Database engine Spring Framework unit test

Opinions expressed by DZone contributors are their own.

Related

  • Camel Route - Unit Testing
  • Spring Boot - Unit Test your project architecture with ArchUnit
  • Data Structures and Indexing for Operations on Deeply Nested Comments
  • Top 10 Advanced Java and Spring Boot Courses for Full-Stack Java Developers

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: