adam bien's blog

In-Memory Java DB 15.0.1.1 - Perfect For JPA-Unit testing 📎

To install Java DB 10.5.1.1 you only have to download a ZIP file, extract it and put two JARs into your classpath. It comes with one major, killer feature - in-memory capability. I used Java DB for test purposes in embedded mode already. The database creates a folder in your local file system, what takes time and requires you to do some plumbing. This mode, however, is perfect if you needed a pre-populate database for your tests. You just had to copy the folder with an existing database into your test-project before your launch the tests and delete it afterwards.

With a in-memory connection: jdbc:derby:memory:sampledb;create=true you can create your database dynamically - and you don't even have to drop the tables afterwards.

To test it, I just adjusted the CRUD-Service configuration and measured the performance again. I didn't have to change anything in the unit-test:


public class CrudServiceBeanTest {

    private EntityManager em;
    private EntityTransaction et;
    private CrudServiceBean crudServiceBean;

    @Before
    public void setUp() throws Exception {
        this.em = Persistence.createEntityManagerFactory("test").createEntityManager();
        this.et = this.em.getTransaction();
        this.crudServiceBean = new CrudServiceBean();
        this.crudServiceBean.em = this.em;
    }
    
    @Test
    public void crud(){
        Book book = new Book("1", "Productive Java EE");

        this.et.begin();

        int initialSize = this.crudServiceBean.findWithNamedQuery(Book.ALL).size();
//... see CRUD Service Example

I only changed one line in the persistence.xml to switch from the embedded to the in-memory mode (Glassfish v2.1 with TopLink):

Embedded mode: <property name="toplink.jdbc.url" value="jdbc:derby:./testDB;create=true"/>

In-Memory mode: <property name="toplink.jdbc.url" value="jdbc:derby:memory:testDB;create=true"/>

In the In-Memory configuration you don't have to drop the tables or clean the database after the tests - it just disappears. You only have to create the tables before the tests. In Glassfish v2 with Toplink you can fall back to the following setting: <property name="toplink.ddl-generation" value="create-tables"/>.

The performance is significantly faster, also in this simple case. The embedded mode took:

Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 2.997 sec

...and the same unit tests on in-memory database:

Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 2.476 sec

H2 and HSQLDB have the in-memory capabilities for ages. Java DB, however, comes with more complete feature-set and is surprisingly DB 2 compatible. The working example was pushed into http://kenai.com/projects/javaee-patterns/ (DAOPattern).

[The code was originally published in this Real World Java EE Patterns book, Page 141