Skip to content

Instantly share code, notes, and snippets.

@beargiles
Last active April 16, 2019 15:03
Show Gist options
  • Save beargiles/d63f1f8819135b5ea78c to your computer and use it in GitHub Desktop.
Save beargiles/d63f1f8819135b5ea78c to your computer and use it in GitHub Desktop.
Create an embedded H2 instance and launch related web console.
During development it's often extremely helpful to write unit and integration tests that launch an
embedded H2 instance with a web console that lets us look into the database. There's no need to write
complicated logging statements when you can just peek at data in the database - especially if you write
your tests to write intermediate results into that database.
A variant of this can be written using @BeforeClass and @AfterClass methods, and some test frameworks
allow the database creation to be handled entirely outside of the classes being tested.
/**
* Simple code to create an embedded H2 server and launch associated web console.
*/
import java.sql.*;
import org.h2.jdbcx.JdbcConnectionPool;
import org.h2.tools.Server;
private static final String URL = "jdbc:h2:~/test;AUTO_SERVER=TRUE";
private static final String USERNAME = "sa";
private static final String PASSWORD = "";
public static void main(String[] args) throws SQLException {
Server server = null;
try {
// create H2 server that supports connections via web page
// we can also use ("-tcp", "-tcpPort", "9090") to specify a TCP port.
// see also ~/.h2.server.properties
Server server = Server.createWebServer("-webAllowOthers", "-browser");
server.start();
// create connection pool
final JdbcConnectionPool cp = JdbcConnectionPool.create(URL, USERNAME, PASSWORD);
// launch web console
try {
new Thread() {
public void run() {
Connection conn = null;
try {
conn = cp.getConnection();
try {
Server.startWebServer(conn);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
} finally {
if (conn != null) {
conn.close();
}
}
}
}.start();
// do work here using connection pool
} finally {
// clean things up.
// terminate thread containing webserver?
// close connection pool.
cp.dispose();
// close underlying H2 database.
if (server != null) {
server.stop();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment