H2 database

H2 is a pure-Java embedded database. That makes it extremely convenient to use in a Java project — there is no extra server software to set up and maintain. It also has some compatibility modes so that, if you want to transition to a separate database server (such as PostgreSQL) later, it shouldn’t be very difficult.

To access H2, add the following Maven library string to your project: com.h2database:h2:1.4.191 — the same way that we added spark-core in M1.

H2 includes a web-based console you can use to run arbitrary SQL on your database file. You can make a run configuration for it in IntelliJ. Select Run » Edit Configurations… Use the green plus sign in the upper right and select Application. Change the name at the top to H2 Console, and in the Main class box, enter org.h2.tools.Console.

Run configuration for H2 Console

Run configuration for H2 Console

When you run the H2 console, it will start a server and then immediately switch to your browser to show the login screen.

H2 Console login screen

H2 Console login screen

For local files and in-memory databases, you shouldn’t need a username or password. So just set the JDBC URL and click Connect. This page has a summary of different JDBC URL formats that are accepted by H2. The most common we’ll use are:

  • jdbc:h2:mem: for a private, in-memory database (note the extra colon at the end)

  • jdbc:h2:~/test for a database file named test in the user’s home directory.

Opening a connection from a Java program looks like this:

import java.sql.*;

public class H2Demo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:mem:");
        // ...
    }
}

Oracle has a JDBC tutorial trail in its Java documentation.