Spring Boot with H2: the embedded database explained
H2 is the database Spring Boot reaches for when you add nothing else: a Java database that runs inside the application. It is ideal for demos and fast tests, as long as you know what it keeps, when it disappears, and where it differs from your production database. This page runs each of those behaviours, from auto-configuration to init scripts and compatibility modes.
Contents
What H2 is, and what Spring Boot does with it
H2 is a relational database written in Java and shipped as a single jar. It can run in three ways: inside your application's JVM with data only in memory, inside the JVM with data in a file, or as a separate server that other processes connect to over TCP. The first is what Spring Boot uses by default, and it is why a new project with spring-boot-starter-data-jpacom.h2database:h2
When an embedded database such as H2 is on the classpath and no spring.datasource.urlsaddl-autocreate-dropschema.sqldata.sql
| URL | Data lives | Best for |
|---|---|---|
jdbc:h2:mem: | In memory, private to one connection | Almost nothing; each connection sees an empty database |
jdbc:h2:mem:name | In memory, shared by name until the last connection closes | Tests that keep a connection open |
jdbc:h2:mem:name;DB_CLOSE_DELAY=-1 | In memory until the JVM exits | Applications and tests with a connection pool |
jdbc:h2:file:./data/app | In a file, app.mv.db | Local development data that survives restarts |
jdbc:h2:tcp://host/~/app | On an H2 server | Several processes sharing one H2 database |
The examples use Spring Boot 4.1 and H2 2.4.240. The URL and compatibility examples use plain JDBC, because they are about H2 itself; Spring Boot passes spring.datasource.url
The auto-configured embedded database
This program starts two application contexts with no database settings at all, as two test classes with different configurations would, then a third one with a fixed database name:
package h2.auto;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootApplication
public class EmbeddedAutoConfig {
static ConfigurableApplicationContext start(Map<String, Object> extra) {
SpringApplication app = new SpringApplication(EmbeddedAutoConfig.class);
Map<String, Object> props = new HashMap<>(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
props.putAll(extra);
app.setDefaultProperties(props);
return app.run();
}
static void describe(String label, ConfigurableApplicationContext context)
throws SQLException {
DataSource dataSource = context.getBean(DataSource.class);
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData meta = connection.getMetaData();
String url = ((HikariDataSource) dataSource).getJdbcUrl()
.replaceAll("[0-9a-f-]{36}", "<random-uuid>");
System.out.println(label);
System.out.println(" DataSource : " + dataSource.getClass().getSimpleName());
System.out.println(" URL : " + url);
System.out.println(" user : " + meta.getUserName());
System.out.println(" database : " + meta.getDatabaseProductName() + " "
+ meta.getDatabaseProductVersion());
}
}
public static void main(String[] args) throws SQLException {
try (var first = start(Map.of());
var second = start(Map.of())) {
describe("First context", first);
new JdbcTemplate(first.getBean(DataSource.class))
.execute("CREATE TABLE note (text VARCHAR(20))");
JdbcTemplate secondJdbc = new JdbcTemplate(second.getBean(DataSource.class));
Integer tables = secondJdbc.queryForObject("SELECT COUNT(*) FROM"
+ " INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'NOTE'", Integer.class);
System.out.println("Second context sees the NOTE table: " + (tables == 1));
}
try (var named = start(Map.of(
"spring.datasource.generate-unique-name", "false",
"spring.datasource.name", "shop"))) {
describe("With generate-unique-name=false and name=shop", named);
}
}
}
First context
DataSource : HikariDataSource
URL : jdbc:h2:mem:<random-uuid>;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
user : SA
database : H2 2.4.240 (2025-09-22)
Second context sees the NOTE table: false
With generate-unique-name=false and name=shop
DataSource : HikariDataSource
URL : jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
user : SA
database : H2 2.4.240 (2025-09-22)
- Spring Boot built a
, the same pool it uses for real databases, pointing atHikariDataSource plus a random UUID. The program replaces the UUID in the output because it changes on every run.jdbc:h2:mem: - The URL ends in
. The first keeps the database alive when the pool closes its last connection; the second lets Spring close it in order at shutdown, instead of H2's own shutdown hook.DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE - The second context did not see the table created through the first one, because each got its own randomly named database. That is
, which isspring.datasource.generate-unique-name by default.true - With
andgenerate-unique-name=false , the URL becamespring.datasource.name=shop . Every context that uses those settings in the same JVM now shares one database, which tests sometimes want and often do not.jdbc:h2:mem:shop - The user is
, H2's upper-case form of Spring Boot's default user nameSA .sa
What each URL mode keeps
The URL decides when an H2 database disappears, and getting it wrong produces "table not found" errors that come and go. This program creates a table through one connection, then looks for it through a new connection, for each mode:
package h2.urls;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Comparator;
import java.util.stream.Stream;
public class UrlModes {
static String tableCount(String url) {
try (Connection c = DriverManager.getConnection(url, "sa", "");
var rs = c.createStatement().executeQuery(
"SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES"
+ " WHERE TABLE_NAME = 'NOTE'")) {
rs.next();
return rs.getInt(1) == 1 ? "NOTE table found" : "no NOTE table";
} catch (SQLException e) {
return "error: " + e.getMessage().lines().findFirst().orElse("");
}
}
static Connection create(String url) throws SQLException {
Connection c = DriverManager.getConnection(url, "sa", "");
try (Statement s = c.createStatement()) {
s.execute("CREATE TABLE note (text VARCHAR(20))");
}
return c;
}
public static void main(String[] args) throws SQLException, IOException {
System.out.println("jdbc:h2:mem: (unnamed)");
Connection unnamed = create("jdbc:h2:mem:");
System.out.println(" second connection : " + tableCount("jdbc:h2:mem:"));
unnamed.close();
System.out.println("jdbc:h2:mem:shop");
Connection shop = create("jdbc:h2:mem:shop");
System.out.println(" while first is open: " + tableCount("jdbc:h2:mem:shop"));
shop.close();
System.out.println(" after it closed : " + tableCount("jdbc:h2:mem:shop"));
System.out.println("jdbc:h2:mem:kept;DB_CLOSE_DELAY=-1");
create("jdbc:h2:mem:kept;DB_CLOSE_DELAY=-1").close();
System.out.println(" after it closed : "
+ tableCount("jdbc:h2:mem:kept;DB_CLOSE_DELAY=-1"));
Path dir = Files.createTempDirectory("h2demo");
String fileUrl = "jdbc:h2:file:" + dir.resolve("app");
System.out.println("jdbc:h2:file:<dir>/app");
create(fileUrl).close();
System.out.println(" after it closed : " + tableCount(fileUrl));
try (Stream<Path> files = Files.list(dir)) {
files.map(p -> " file on disk: " + p.getFileName()).forEach(System.out::println);
}
System.out.println(" IFEXISTS=TRUE on a missing file: "
+ tableCount("jdbc:h2:file:" + dir.resolve("other") + ";IFEXISTS=TRUE")
.replace(dir.toString(), "<dir>"));
try (Stream<Path> files = Files.walk(dir)) {
files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
}
jdbc:h2:mem: (unnamed)
second connection : no NOTE table
jdbc:h2:mem:shop
while first is open: NOTE table found
after it closed : no NOTE table
jdbc:h2:mem:kept;DB_CLOSE_DELAY=-1
after it closed : NOTE table found
jdbc:h2:file:<dir>/app
after it closed : NOTE table found
file on disk: app.mv.db
IFEXISTS=TRUE on a missing file: error: Database "<dir>/other" not found, and IFEXISTS=true, so we cant auto-create it [90146-240]
with no name is private to its connection: a second connection to the same URL opened a different, empty database.jdbc:h2:mem: was shared while the first connection was open, and gone once it closed. H2 drops a named in-memory database when its last connection closes.jdbc:h2:mem:shop- With
, the table survived the close. The database now lives until the JVM exits, which is why Spring Boot adds this setting to its embedded URLs.DB_CLOSE_DELAY=-1 stored the database injdbc:h2:file: , and a new connection found the table. The file survives restarts of the application.app.mv.db- A file URL creates the database if it does not exist.
refuses instead, which protects against typos in the path.IFEXISTS=TRUE
A connection pool hides the first trap: with spring.datasource.url=jdbc:h2:mem:testDB_CLOSE_DELAYDB_CLOSE_DELAY=-1AUTO_SERVER=TRUE
schema.sql and data.sql
Spring Boot can create tables and test data from SQL scripts at startup. By default it runs classpath:schema.sqlclasspath:data.sqlspring.sql.init.mode=embedded
CREATE TABLE city (
id INT PRIMARY KEY,
name VARCHAR(40) NOT NULL,
population INT
);
INSERT INTO city VALUES (1, 'Lisbon', 545000);
INSERT INTO city VALUES (2, 'Porto', 232000);
INSERT INTO city VALUES (3, 'Braga', 193000);
package h2.init;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootApplication
public class SqlInitScripts {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(SqlInitScripts.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"spring.jpa.hibernate.ddl-auto", "none",
"spring.sql.init.schema-locations", "classpath:h2init/schema.sql",
"spring.sql.init.data-locations", "classpath:h2init/data.sql"));
try (var context = app.run(args)) {
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
jdbc.query("SELECT name, population FROM city ORDER BY population DESC",
(rs, row) -> rs.getString(1) + " " + rs.getInt(2))
.forEach(System.out::println);
}
}
}
Lisbon 545000
Porto 232000
Braga 193000
The three cities came from data.sqlspring.sql.init.schema-locationsdata-locationsspring.jpa.hibernate.ddl-auto=nonespring.sql.init.mode=alwaysspring.sql.init.platform=h2schema-h2.sqldata-h2.sqlcontinue-on-error=true
data.sql with JPA: the ordering trap
With JPA, Hibernate creates the tables from the entities, and data.sqlDataSourcedata.sqlProduct
INSERT INTO product (id, name, price) VALUES (1, 'Desk', 199.00);
INSERT INTO product (id, name, price) VALUES (2, 'Lamp', 24.99);
package h2.defer;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
@SpringBootApplication
public class DeferredInit {
static void run(boolean defer) {
SpringApplication app = new SpringApplication(DeferredInit.class);
Map<String, Object> props = new HashMap<>(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "OFF",
"spring.sql.init.data-locations", "classpath:h2jpa/data.sql"));
props.put("spring.jpa.defer-datasource-initialization", String.valueOf(defer));
app.setDefaultProperties(props);
System.out.println("defer-datasource-initialization=" + defer);
try (var context = app.run()) {
System.out.println(" products: "
+ context.getBean(ProductRepository.class).findAll());
} catch (RuntimeException e) {
Throwable cause = e;
while (cause.getCause() != null) {
cause = cause.getCause();
}
System.out.println(" startup failed: " + cause.getMessage().lines().findFirst()
.orElse(""));
}
}
public static void main(String[] args) {
run(false);
run(true);
}
}
@Entity
class Product {
@Id
private Long id;
private String name;
private BigDecimal price;
protected Product() {
}
@Override
public String toString() {
return name + " " + price;
}
}
interface ProductRepository extends JpaRepository<Product, Long> {
}
defer-datasource-initialization=false
startup failed: Table "PRODUCT" not found (this database is empty); SQL statement:
defer-datasource-initialization=true
products: [Desk 199.00, Lamp 24.99]
- With the default
, the script ran against an empty database and startup failed:spring.jpa.defer-datasource-initialization=false .Table "PRODUCT" not found - With
, Spring Boot ran the script after thetrue had created the schema, and both products were loaded.EntityManagerFactory
Do not mix the two ways of creating tables: either let Hibernate create them and use only data.sqlschema.sqlddl-auto=none
Compatibility modes and their limits
H2 can imitate other databases with a MODEPostgreSQLMySQLMariaDBOracleMSSQLServerDB2DerbyHSQLDB
package h2.modes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class CompatibilityModes {
static final List<String> STATEMENTS = List.of(
"INSERT INTO item VALUES (1, 'b') ON CONFLICT DO NOTHING",
"INSERT INTO item VALUES (1, 'b') ON DUPLICATE KEY UPDATE name = 'b'",
"SELECT '{\"a\": 1}'::jsonb",
"SELECT '{\"a\": 1}'::jsonb ->> 'a'",
"SELECT jsonb_build_object('a', 1)");
static void run(String label, String url) throws SQLException {
System.out.println(label);
try (Connection c = DriverManager.getConnection(url, "sa", "");
Statement s = c.createStatement()) {
s.execute("CREATE TABLE item (id INT PRIMARY KEY, name VARCHAR(20))");
s.execute("INSERT INTO item VALUES (1, 'a')");
for (String sql : STATEMENTS) {
try {
String result = "ok";
if (s.execute(sql)) {
try (ResultSet rs = s.getResultSet()) {
rs.next();
result = "ok, returned " + rs.getString(1);
}
}
System.out.println(" " + result + " <- " + sql);
} catch (SQLException e) {
System.out.println(" " + e.getClass().getSimpleName() + " <- " + sql);
}
}
}
}
public static void main(String[] args) throws SQLException {
run("Regular mode", "jdbc:h2:mem:regular");
run("MODE=PostgreSQL", "jdbc:h2:mem:pg;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE");
run("MODE=MySQL", "jdbc:h2:mem:mysql;MODE=MySQL;DATABASE_TO_LOWER=TRUE");
}
}
Regular mode
JdbcSQLSyntaxErrorException <- INSERT INTO item VALUES (1, 'b') ON CONFLICT DO NOTHING
JdbcSQLSyntaxErrorException <- INSERT INTO item VALUES (1, 'b') ON DUPLICATE KEY UPDATE name = 'b'
JdbcSQLNonTransientException <- SELECT '{"a": 1}'::jsonb
JdbcSQLNonTransientException <- SELECT '{"a": 1}'::jsonb ->> 'a'
JdbcSQLSyntaxErrorException <- SELECT jsonb_build_object('a', 1)
MODE=PostgreSQL
ok <- INSERT INTO item VALUES (1, 'b') ON CONFLICT DO NOTHING
JdbcSQLSyntaxErrorException <- INSERT INTO item VALUES (1, 'b') ON DUPLICATE KEY UPDATE name = 'b'
ok, returned "{\"a\": 1}" <- SELECT '{"a": 1}'::jsonb
JdbcSQLSyntaxErrorException <- SELECT '{"a": 1}'::jsonb ->> 'a'
JdbcSQLSyntaxErrorException <- SELECT jsonb_build_object('a', 1)
MODE=MySQL
JdbcSQLSyntaxErrorException <- INSERT INTO item VALUES (1, 'b') ON CONFLICT DO NOTHING
ok <- INSERT INTO item VALUES (1, 'b') ON DUPLICATE KEY UPDATE name = 'b'
JdbcSQLNonTransientException <- SELECT '{"a": 1}'::jsonb
JdbcSQLNonTransientException <- SELECT '{"a": 1}'::jsonb ->> 'a'
JdbcSQLSyntaxErrorException <- SELECT jsonb_build_object('a', 1)
- PostgreSQL's
worked only in PostgreSQL mode, and MySQL'sON CONFLICT DO NOTHING only in MySQL mode. Regular mode rejected both.ON DUPLICATE KEY UPDATE - In PostgreSQL mode, the
cast was accepted, but it returned the JSON text wrapped in quotes as a JSON string,::jsonb , not the object PostgreSQL would return. The statement passed and the result was different."{\"a\": 1}" - The
operator and->> failed in every mode: H2 implements a subset of each database, not the database.jsonb_build_object
DATABASE_TO_LOWER=TRUE
The H2 web console
H2 includes a browser console for running SQL against a database. Spring Boot can serve it from a servlet web application at /h2-console
- Spring Boot 4: the console support moved to its own module, so add
as well as H2. In Spring Boot 3 it was part of the main auto-configuration. The module's auto-configuration needs H2'sorg.springframework.boot:spring-boot-h2console and a servlet web application, hereJakartaWebServlet .spring-boot-starter-webmvc - Enabling:
defaults tospring.h2.console.enabled . The module also ships a DevTools default offalse , so with DevTools on the classpath the console is on without the setting.true - Path:
changes it fromspring.h2.console.path ./h2-console - Connecting: enter the JDBC URL the application uses. With the default random name, the URL is logged at startup; setting
gives the fixedspring.datasource.generate-unique-name=false .jdbc:h2:mem:testdb
The console is meant for a browser, but its pages are plain HTTP, so a program can walk through the same steps a browser takes: open the console, log in with the application's URL, and run a query. This program starts the application on a random port with the console enabled, creates a table through JdbcTemplate
package h2.console;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootApplication
public class ConsoleDemo {
static final HttpClient CLIENT = HttpClient.newHttpClient();
static ConfigurableApplicationContext start(Map<String, Object> extra) {
SpringApplication app = new SpringApplication(ConsoleDemo.class);
Map<String, Object> props = new HashMap<>(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"logging.pattern.console", "%-5level %logger{0} : %msg%n",
"logging.level.org.springframework.boot.h2console", "INFO",
"server.port", "0",
"spring.jpa.open-in-view", "false",
"spring.datasource.generate-unique-name", "false"));
props.putAll(extra);
app.setDefaultProperties(props);
return app.run();
}
static HttpResponse<String> send(String url, String form)
throws IOException, InterruptedException {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url));
if (form != null) {
request.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form));
}
return CLIENT.send(request.build(), HttpResponse.BodyHandlers.ofString());
}
static String base(ConfigurableApplicationContext context) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
return "http://localhost:" + port + "/h2-console";
}
public static void main(String[] args) throws Exception {
try (var context = start(Map.of("spring.h2.console.enabled", "true"))) {
new JdbcTemplate(context.getBean(DataSource.class)).execute(
"CREATE TABLE city (id INT PRIMARY KEY, name VARCHAR(20));"
+ " INSERT INTO city VALUES (1, 'Lisbon'), (2, 'Porto')");
String base = base(context);
HttpResponse<String> noSlash = send(base, null);
String location = noSlash.headers().firstValue("Location").orElse("");
System.out.println("GET /h2-console -> " + noSlash.statusCode()
+ ", Location ends with " + location.replaceAll(".*/h2", "/h2"));
HttpResponse<String> welcome = send(base + "/", null);
Matcher id = Pattern.compile("jsessionid=(\\w+)").matcher(welcome.body());
id.find();
String session = "?jsessionid=" + id.group(1);
System.out.println("GET /h2-console/ -> " + welcome.statusCode()
+ ", script sends the browser to login.jsp?jsessionid=<id>");
HttpResponse<String> login = send(base + "/login.do" + session,
"driver=org.h2.Driver&url=jdbc%3Ah2%3Amem%3Atestdb&user=sa&password=");
System.out.println("POST login.do -> " + login.statusCode()
+ ", frames: " + login.body().contains("<frameset"));
HttpResponse<String> query = send(base + "/query.do" + session,
"sql=SELECT+*+FROM+city+ORDER+BY+id");
String table = query.body().replaceAll("(?s).*<table class=\"resultSet\"", "")
.replaceAll("(?s)</table>.*", "");
System.out.println("POST query.do -> " + query.statusCode()
+ ", SELECT * FROM city ORDER BY id");
for (String row : table.split("<tr>")) {
String cells = row.replaceAll("</t[hd]>", " | ").replaceAll("<[^>]+>", "").trim();
if (!cells.isEmpty() && !cells.startsWith("cellspacing")) {
System.out.println(" | " + cells);
}
}
}
try (var context = start(Map.of())) {
System.out.println("Without spring.h2.console.enabled:");
System.out.println("GET /h2-console/ -> " + send(base(context) + "/", null)
.statusCode());
}
}
}
INFO H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
GET /h2-console -> 302, Location ends with /h2-console/
GET /h2-console/ -> 200, script sends the browser to login.jsp?jsessionid=<id>
POST login.do -> 200, frames: true
POST query.do -> 200, SELECT * FROM city ORDER BY id
| ID | NAME |
| 1 | Lisbon |
| 2 | Porto |
Without spring.h2.console.enabled:
GET /h2-console/ -> 404
- The INFO line is the one the console module logs at startup. It names the path and the database URL to type into the login form, here
because unique names are switched off.jdbc:h2:mem:testdb without a slash answered 302 and redirected to/h2-console . The console page answered 200 with a script that moves the browser to/h2-console/ with a console session id, which the program reads from the page.login.jsp- Posting the driver, URL, user
and empty password tosa returned the console's frame set. The query then returned the two rows the application had inserted, because the console connected to the same in-memory database inside the same JVM.login.do - Without
, the same path answered 404: the module was on the classpath, but it registered no servlet.spring.h2.console.enabled
The demo class is called ConsoleDemoh2Console@SpringBootApplicationH2Console
The console runs any SQL it is given, so it must never be enabled in production. By default, spring.h2.console.settings.web-allow-othersfalse
Choosing how to use H2
| Need | Setup |
|---|---|
| A quick demo or prototype | The auto-configured database, with no settings |
| Fast tests of JPA mappings and simple queries | The auto-configured database, one per context with generate-unique-name |
| Local data that survives restarts | jdbc:h2:file:./data/app |
| Test data for JPA entities | data.sqlspring.jpa.defer-datasource-initialization=true |
| Keeping simple SQL portable | MODE=PostgreSQLMODE=MySQLDATABASE_TO_LOWER=TRUE |
| Database-specific SQL, migrations, production behaviour | The real database, in Docker with Testcontainers |
| Production | Not H2; a server database with backups and monitoring |
H2 is used in every example of the