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-jpa and the com.h2database:h2 dependency starts without any database settings.

When an embedded database such as H2 is on the classpath and no spring.datasource.url is set, Spring Boot creates a connection pool to a fresh in-memory database, with user sa and an empty password. It also changes some defaults for that case: Hibernate's ddl-auto becomes create-drop, and the schema.sql and data.sql scripts run automatically.

H2 connection URL forms
URLData livesBest for
jdbc:h2:mem:In memory, private to one connectionAlmost nothing; each connection sees an empty database
jdbc:h2:mem:nameIn memory, shared by name until the last connection closesTests that keep a connection open
jdbc:h2:mem:name;DB_CLOSE_DELAY=-1In memory until the JVM exitsApplications and tests with a connection pool
jdbc:h2:file:./data/appIn a file, app.mv.dbLocal development data that survives restarts
jdbc:h2:tcp://host/~/appOn an H2 serverSeveral 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 to H2 unchanged.

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:

Java
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);
        }
    }
}
Output
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 HikariDataSource, the same pool it uses for real databases, pointing at jdbc:h2:mem: plus a random UUID. The program replaces the UUID in the output because it changes on every run.
  • The URL ends in DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE. 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.
  • The second context did not see the table created through the first one, because each got its own randomly named database. That is spring.datasource.generate-unique-name, which is true by default.
  • With generate-unique-name=false and spring.datasource.name=shop, the URL became jdbc:h2:mem:shop. Every context that uses those settings in the same JVM now shares one database, which tests sometimes want and often do not.
  • The user is SA, H2's upper-case form of Spring Boot's default user name 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:

Java
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());
        }
    }
}
Output
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]
  • jdbc:h2:mem: with no name is private to its connection: a second connection to the same URL opened a different, empty database.
  • jdbc:h2:mem:shop 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.
  • With DB_CLOSE_DELAY=-1, 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.
  • jdbc:h2:file: stored the database in app.mv.db, and a new connection found the table. The file survives restarts of the application.
  • A file URL creates the database if it does not exist. IFEXISTS=TRUE refuses instead, which protects against typos in the path.

A connection pool hides the first trap: with spring.datasource.url=jdbc:h2:mem:test and no DB_CLOSE_DELAY, the database survives only while the pool holds a connection. If the pool closes idle connections, the schema is gone. Always add DB_CLOSE_DELAY=-1 when you set an in-memory URL yourself. A file database has a different limit: H2 locks the file, so only one process can open it at a time. A second application, or a database tool opened while the application runs, fails to connect. Adding AUTO_SERVER=TRUE to the URL makes the first process start a small server that later processes connect through automatically.

schema.sql and data.sql

Spring Boot can create tables and test data from SQL scripts at startup. By default it runs classpath:schema.sql and then classpath:data.sql, but only for embedded databases (spring.sql.init.mode=embedded). This program points to scripts in a folder, so they apply only to it:

SQL
CREATE TABLE city (
    id         INT PRIMARY KEY,
    name       VARCHAR(40) NOT NULL,
    population INT
);
SQL
INSERT INTO city VALUES (1, 'Lisbon', 545000);
INSERT INTO city VALUES (2, 'Porto', 232000);
INSERT INTO city VALUES (3, 'Braga', 193000);
Java
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);
        }
    }
}
Output
Lisbon 545000
Porto 232000
Braga 193000

The three cities came from data.sql, ordered by population. Two settings in the program matter: spring.sql.init.schema-locations and data-locations select the scripts, and spring.jpa.hibernate.ddl-auto=none stops Hibernate from creating tables too, since the JPA starter is on the classpath. Other useful settings are spring.sql.init.mode=always to run the scripts against a real database, spring.sql.init.platform=h2 to pick schema-h2.sql and data-h2.sql, and continue-on-error=true to log failing statements instead of stopping startup.

data.sql with JPA: the ordering trap

With JPA, Hibernate creates the tables from the entities, and data.sql fills them. But by default the scripts run when the DataSource is ready, which is before Hibernate has created anything. This data.sql inserts into the table of the Product entity:

SQL
INSERT INTO product (id, name, price) VALUES (1, 'Desk', 199.00);
INSERT INTO product (id, name, price) VALUES (2, 'Lamp', 24.99);
Java
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> {
}
Output
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 spring.jpa.defer-datasource-initialization=false, the script ran against an empty database and startup failed: Table "PRODUCT" not found.
  • With true, Spring Boot ran the script after the EntityManagerFactory had created the schema, and both products were loaded.

Do not mix the two ways of creating tables: either let Hibernate create them and use only data.sql with deferral, or create them with schema.sql and set ddl-auto=none. For anything beyond test data, a migration tool is the better choice; Flyway and Liquibase both run against H2.

Compatibility modes and their limits

H2 can imitate other databases with a MODE setting in the URL: PostgreSQL, MySQL, MariaDB, Oracle, MSSQLServer, DB2, Derby and HSQLDB. Each mode accepts some of that database's syntax. These statements are typical of PostgreSQL and MySQL code, and each mode runs all of them:

Java
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");
    }
}
Output
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 ON CONFLICT DO NOTHING worked only in PostgreSQL mode, and MySQL's ON DUPLICATE KEY UPDATE only in MySQL mode. Regular mode rejected both.
  • In PostgreSQL mode, the ::jsonb cast was accepted, but it returned the JSON text wrapped in quotes as a JSON string, "{\"a\": 1}", not the object PostgreSQL would return. The statement passed and the result was different.
  • The ->> operator and jsonb_build_object failed in every mode: H2 implements a subset of each database, not the database.

DATABASE_TO_LOWER=TRUE, used with PostgreSQL and MySQL modes, makes unquoted names lower case as those databases do. Compatibility modes are useful for keeping simple queries portable. For SQL that uses database-specific features, such as JSON, arrays, window functions or full-text search, test against the real database; Testcontainers starts one in Docker for each test run.

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. The setup has changed in Spring Boot 4, and the console has a few conditions:

  • Spring Boot 4: the console support moved to its own module, so add org.springframework.boot:spring-boot-h2console as well as H2. In Spring Boot 3 it was part of the main auto-configuration. The module's auto-configuration needs H2's JakartaWebServlet and a servlet web application, here spring-boot-starter-webmvc.
  • Enabling: spring.h2.console.enabled defaults to false. The module also ships a DevTools default of true, so with DevTools on the classpath the console is on without the setting.
  • Path: spring.h2.console.path changes it from /h2-console.
  • Connecting: enter the JDBC URL the application uses. With the default random name, the URL is logged at startup; setting spring.datasource.generate-unique-name=false gives the fixed 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, and then queries it through the console. A second application without the setting shows what happens when it is off.

Java
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());
        }
    }
}
Output
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 jdbc:h2:mem:testdb because unique names are switched off.
  • /h2-console without a slash answered 302 and redirected to /h2-console/. The console page answered 200 with a script that moves the browser to login.jsp with a console session id, which the program reads from the page.
  • Posting the driver, URL, user sa and empty password to login.do 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.
  • Without spring.h2.console.enabled, the same path answered 404: the module was on the classpath, but it registered no servlet.

The demo class is called ConsoleDemo for a reason. The auto-configuration registers its servlet as a bean named h2Console, and a @SpringBootApplication class named H2Console gets the same bean name. When the class had that name, startup failed with "The bean 'h2Console' ... could not be registered. A bean with that name has already been defined and overriding is disabled."

The console runs any SQL it is given, so it must never be enabled in production. By default, spring.h2.console.settings.web-allow-others is false, which accepts only connections from the local machine. With Spring Security on the classpath, the console's frames and forms are also blocked by default, and its path needs its own security rules.

Choosing how to use H2

H2 setups for common needs
NeedSetup
A quick demo or prototypeThe auto-configured database, with no settings
Fast tests of JPA mappings and simple queriesThe auto-configured database, one per context with generate-unique-name
Local data that survives restartsjdbc:h2:file:./data/app
Test data for JPA entitiesdata.sql with spring.jpa.defer-datasource-initialization=true
Keeping simple SQL portableMODE=PostgreSQL or MODE=MySQL, with DATABASE_TO_LOWER=TRUE
Database-specific SQL, migrations, production behaviourThe real database, in Docker with Testcontainers
ProductionNot H2; a server database with backups and monitoring

H2 is used in every example of the Spring Data JPA pages, and the JDBC basics page shows it without Spring. To connect to more than one database at once, see multiple data sources.