Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Spring Boot starts an in-memory H2 database when it is on the classpath and no URL is set. How does this work, how do you load a schema, and why is H2 a poor substitute for PostgreSQL in tests?

When H2 is on the classpath and spring.datasource.url is not set, Spring Boot creates an embedded in-memory database with a generated unique name, such as jdbc:h2:mem:<uuid>, that lives exactly as long as the application. The schema comes from schema.sql and data.sql, from Hibernate's ddl-auto, or from Flyway or Liquibase migrations. H2 is a poor substitute for PostgreSQL in tests because its compatibility mode imitates only part of PostgreSQL, so types, functions, locking and isolation differ; we prefer Testcontainers with the real database version, which Boot 3.1+ wires in with @ServiceConnection.

Why this question is asked

H2 made Spring Boot demos famous: add one dependency, start the application, and there is a working database with no installation at all. Many test suites still rely on it for the same reason. Interviewers ask about it because it reveals two things: whether we know what Boot's auto-configuration does behind the scenes, and whether we have learned, usually the hard way, that a test passing on H2 says little about PostgreSQL. In this answer, we will see how Boot decides to start an embedded database, how the schema gets loaded, why H2 differs from PostgreSQL in ways that matter, and what to use instead.

1How Boot Decides to Start an Embedded Database

An embedded database runs inside our own Java process instead of on a separate server. H2, HSQLDB and Derby can all run this way, and with the mem mode the data lives only in memory, so it disappears when the process stops.

Spring Boot's DataSource auto-configuration checks two things. If no spring.datasource.url is set, and an embedded database driver such as H2 is on the classpath, Boot creates a DataSource for an in-memory database instead of failing. By default it generates a unique name for it (spring.datasource.generate-unique-name is true), so the URL looks like jdbc:h2:mem: followed by a random identifier. The unique name matters in tests: two Spring contexts in the same JVM get two separate databases instead of sharing and corrupting each other's data.

Boot also keeps the database alive while the application runs. Normally an H2 in-memory database is dropped when its last connection closes; the URL Boot builds keeps it open until the JVM shuts down, so a connection pool that closes and reopens connections does not lose the data.

XML
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
// No spring.datasource.url in application.yml; at startup the log shows something like:
// H2 console available ... Database available at 'jdbc:h2:mem:4f1c2a7e-...' (when the console is enabled)

2Loading the Schema and Data

An empty database needs tables. Boot offers three ways, and it is best to choose exactly one. The first is SQL scripts: schema.sql and data.sql on the classpath run at startup. For embedded databases this is the default, because spring.sql.init.mode is embedded; for a real database we would set it to always.

The second is Hibernate's schema generation. With JPA and an embedded database, and no migration tool present, Boot sets spring.jpa.hibernate.ddl-auto to create-drop, so Hibernate creates tables from the entities at startup. The third, and the one that matches production, is a migration tool: with Flyway or Liquibase on the classpath, Boot runs the migrations against the embedded database just as it would against PostgreSQL.

Java
-- src/main/resources/schema.sql
CREATE TABLE customer (id BIGINT PRIMARY KEY, name VARCHAR(100) NOT NULL);
-- src/main/resources/data.sql
INSERT INTO customer VALUES (1, 'Asha');
// In a test
Integer n = jdbc.sql("SELECT count(*) FROM customer").query(Integer.class).single(); // 1

There is one ordering trap. When we use data.sql together with Hibernate's ddl-auto, the scripts run before Hibernate creates the tables by default, so the inserts fail. Setting spring.jpa.defer-datasource-initialization=true makes the scripts wait for Hibernate. Mixing script initialisation with Flyway is not supported in the same way, which is another reason to pick one mechanism.

3Why H2 Is a Poor Substitute for PostgreSQL

H2 has compatibility modes, such as MODE=PostgreSQL in the URL, that make it accept some PostgreSQL syntax and imitate some behaviour. But it is still a different database engine with its own parser, types, functions and concurrency model. The mode covers part of the dialect, not the whole of it.

The differences fall into a few groups. Types: PostgreSQL's jsonb, arrays with their operators, range types, citext and many others are missing or behave differently. Functions and syntax: things like ON CONFLICT details, generate_series, window function edge cases, full-text search and specific date functions differ or are missing. Concurrency: locking, SELECT ... FOR UPDATE SKIP LOCKED behaviour and what each isolation level actually guarantees differ, so tests about race conditions prove nothing. Even ordering of NULLs and case sensitivity rules can differ.

Where H2 in PostgreSQL mode and real PostgreSQL differ
AreaPostgreSQLH2 (MODE=PostgreSQL)
jsonb columns and operatorsNative type, ->>, @>, GIN indexesNot supported as PostgreSQL defines them
Arrays and rangesRich operators and index supportPartial or different semantics
Locking and isolationMVCC with PostgreSQL's rulesIts own engine and rules
Extensions (pg_trgm, PostGIS)AvailableNot available
Error codes and messagesPostgreSQL SQLSTATEsH2's own codes
Check your H2 version for details; the list of gaps changes, but it never reaches zero.

4The Two Ways Tests Lie

These differences make tests wrong in both directions. A test can pass on H2 and fail in production: a query that H2 accepts may behave differently on PostgreSQL, a constraint name may differ, or a race condition test passes because H2 locks differently. And a test can fail on H2 for perfectly valid PostgreSQL SQL: the moment we use jsonb or a PostgreSQL function, the test suite breaks, and the team is pushed toward writing only SQL that both engines understand, which means not using the database we actually pay for.

Either way, the test suite stops telling the truth about production, which is the only reason it exists.

5What to Use Instead: Testcontainers With @ServiceConnection

Testcontainers starts a real database in a Docker container for the tests. With the same image version as production, for example postgres:17, the tests run against the same engine, types and behaviour. Since Spring Boot 3.1, the @ServiceConnection annotation tells Boot to read the container's URL, username and password and configure the DataSource from them, so no properties are needed.

Java
@TestConfiguration(proxyBeanMethods = false)
class PostgresTestConfig {
@Bean
@ServiceConnection
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>("postgres:17"); // same major version as production
}
}
@SpringBootTest
@Import(PostgresTestConfig.class)
class OrderRepositoryTest {
@Test void savesJsonb() { ... } // runs the real Flyway migrations on real PostgreSQL
}

Notice that the container is a bean, so Spring's test context cache reuses it for every test class that shares the same configuration. The startup cost, a few seconds, is paid once per test run, not once per test. The package of PostgreSQLContainer moved in newer Testcontainers releases, so check your version for the import.

6Follow-up questions

When is H2 still a reasonable choice?

H2 is fine where the database is incidental rather than the thing being tested: a quick prototype or demo, a tutorial, a small tool whose SQL is deliberately portable, or tests for a library that must work on many databases and is also tested on the real ones. It is also handy in environments where Docker is not available, as long as everyone understands those tests are not proof of production behaviour. For a service that runs on PostgreSQL and uses its features, integration tests should use PostgreSQL.

Should we keep the H2 dependency once we move to Testcontainers?

Usually no. If H2 stays on the test classpath, it is easy for a new test to fall back to it silently when nothing else is configured. Removing it makes the choice explicit, and Boot's @AutoConfigureTestDatabase replacement behaviour in @DataJpaTest is then disabled or pointed at the container, so check how your test slices are configured.

Do the extra seconds of container startup matter?

For integration tests, rarely. One shared container per test run costs a few seconds, while a bug that only appears on PostgreSQL can cost hours. We keep unit tests free of any database so they stay instant, and run the container-backed tests as a separate, slightly slower group.

7Conclusion

In this answer, we saw that Spring Boot starts an embedded in-memory H2 database, with a unique generated name and a lifetime equal to the application's, whenever H2 is on the classpath and no URL is configured. The schema comes from schema.sql and data.sql, Hibernate's ddl-auto, or migrations, and it is best to pick one. Because H2's PostgreSQL mode only imitates part of PostgreSQL, tests can pass on H2 and fail in production, or fail on valid PostgreSQL SQL, so integration tests should use Testcontainers with the production database version, wired in with @ServiceConnection.

What to say in the interviewAbout 80 seconds aloud

Open with

If H2 is on the classpath and I do not set spring.datasource.url, Boot's DataSource auto-configuration falls back to an embedded database. It generates a unique name, so the URL is jdbc:h2:mem with a random id, which keeps different test contexts apart, and the database lives as long as the application.

Then, if they want more

For the schema, Boot runs schema.sql and data.sql by default for embedded databases, or Hibernate creates tables with ddl-auto create-drop, or Flyway or Liquibase run migrations if they are present; I would pick one, ideally the same migrations as production. If I mix data.sql with Hibernate, I need defer-datasource-initialization.

The problem with H2 as a stand-in for PostgreSQL is that compatibility mode only covers part of the dialect. jsonb, arrays, extensions, many functions, locking and isolation behaviour all differ. So tests can pass on H2 and fail in production, or fail on perfectly valid PostgreSQL SQL, which pushes the team toward lowest-common-denominator SQL.

For integration tests I use Testcontainers with the same PostgreSQL version as production, and since Boot 3.1 a container bean with @ServiceConnection configures the DataSource automatically. H2 is still fine for demos or genuinely portable code.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3.1
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
java.sql, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Spring Boot starts an in-memory H2 database when it is on the classpath and no URL is...": https://scrivio-interview-library.netlify.app/databases/jdbc/bc1eb62f20/