Using an embedded SQL database in Java web application

You have a Java web application needing a relational SQL database. According to JavaEE conventions, you declare the DataSource in web.xml:


and then fetch it in code with (DataSource)new InitialContext().lookup("java:comp/env/jdbc/DS").

Using Maven, Jetty and HSQLDB, you can very easily run the web application for local testing without having to setup neither a web container, nor a database. Add this to pom.xml:


And add a file src/etc/jetty-ds.xml to your project:

<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "">
<Configure id="wac" class="org.eclipse.jetty.webapp.WebAppContext">
  <New id="DS" class="">
    <Arg><Ref refid="wac"/></Arg>
      <New class="org.hsqldb.jdbc.JDBCDataSource">
        <Set name="DatabaseName">mem:db</Set>
        <Set name="User">SA</Set>
        <Set name="Password">""</Set>

Then run it locally with mvn jetty:run. The database will be in-memory and does not presist between runs. It is also possible to configure HSQLDB to persist data on disk, see documentation.

If you want to have access to in-memory database in your tests, add this dependency to pom.xml:


And create the DataSource in your test code like this:

import org.hsqldb.jdbc.JDBCDataSource;

        JDBCDataSource hsqldbDs = new JDBCDataSource();

Note: This will not add the DataSource to JNDI.

This entry was posted in Java, JavaEE, web. Bookmark the permalink.

4 Responses to Using an embedded SQL database in Java web application

  1. Hi Mikal,

    this is a very good example – just one little typo:

    should be

  2. 2nd try, as the xml tags are not displayed:

    <Arg><Ref id=”wac”/></Arg>

    should be

    <Arg><Ref refid=”wac”/></Arg>

Leave a Reply

Your email address will not be published. Required fields are marked *

(this is a captcha)