Skip to content

Instantly share code, notes, and snippets.

@kimble
Last active August 29, 2015 14:27
Show Gist options
  • Save kimble/bb91263f7c5f7abaafd9 to your computer and use it in GitHub Desktop.
Save kimble/bb91263f7c5f7abaafd9 to your computer and use it in GitHub Desktop.
H2Rule.java
package junit.rules;
import org.h2.jdbcx.JdbcConnectionPool;
import org.junit.rules.ExternalResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.function.Consumer;
public class H2Rule extends ExternalResource {
private final static Logger log = LoggerFactory.getLogger(H2Rule.class);
private final String dbName;
private JdbcConnectionPool connectionPool;
private Connection keepAliveConnection;
public H2Rule(String dbName) {
this.dbName = dbName;
}
@Override
protected void before() throws Throwable {
connectionPool = JdbcConnectionPool.create("jdbc:h2:mem:" + dbName, "sa", "sa"); // <1>
keepAliveConnection = connectionPool.getConnection(); // <2>
}
public Connection openConnection() throws SQLException {
return connectionPool.getConnection();
}
public void withConnection(Consumer<Connection> consumer) throws SQLException {
try (Connection connection = openConnection()) {
consumer.accept(connection);
}
}
// <3>
@Override
protected void after() {
if (keepAliveConnection != null) {
try {
keepAliveConnection.close();
}
catch (SQLException ex) {
log.warn("Failed to close connection used to keep H2 database open during test execution", ex);
}
}
if (connectionPool != null) {
connectionPool.dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment