Using the H2 Console in Spring and IntelliJ

Like many developers I use H2 Database for building and testing Spring Boot apps. Using an In-Memory database for creating and destroying data with each build is efficient, but viewing the data while the application is running is problematic.

Enter H2 Console. Here's the NixMash Spring app's Contacts table viewed in H2 Console while the app is running.

Notice the http://localhost:8084/console url in the address above. My application is configured to use http://localhost:8084. You can integrate the H2 Console to work seamlessly with your app in Spring by adding the following code to any Configuration file that extends WebSecurityConfigurerAdapter. You can completely ignore the port assignment here. That is, if your app is running at a non-8080 port like mine is it has no effect on H2 Console.

Our configure() method enables using /console with Spring Security. We're also registering an org.h2.server.web.WebServlet when running Spring with the H2 Profile.

One final point to make on this configuration. You can use the same H2.jar you're already using with your application. No need to download or install anything additional.

The Persistent Database Fallback

With the above configuration you can fire up your Spring Boot app and go to /console where the H2 Console login page will be waiting. At this point enter jdbc:h2:mem:testdb or whatever url you are using for your In-Memory H2 database.

If you don't want to go the above route you can always go with the Persistent Database Fallback to use H2 Console while running your application. This requires no Spring configuration at all. Simply output to a file H2 Database rather than an in-memory database then fire up your h2.jar and point to the database file. Here's how that would work.

First set your H2 Url to output to file. Something like jdbc:h2:file:testdb. (“file” instead of “mem”.) When we run the app our H2 database is in our root directory.

Now we go to a terminal (preferably a sweet integrated terminal like in IntelliJ) and execute our H2 JAR file which we've placed somewhere in our path. I renamed the JAR to h2Console.jar.

At that point the H2 Console login page will appear and we enter the url to our H2 database file. Here's a tip for IntelliJ IDEA users. To obtain the Url of the H2 Database, drag the H2 database into IntelliJ's Database View. You can't open it because it is locked (thus the need for H2 Console), but if you click on “Properties” you'll see the Url to the database. Shown in blue here.

The source code in this post is available in branch v0.1.6 of NixMash Spring on GitHub.

Posted July 17, 2015 10:05 AM EDT

More Like This Post