Labs ICT
โญ Pro Login

H2 Database

Using the in-memory database for development.

H2 Database

When you're learning or prototyping, you don't want to set up a full database server. That's where H2 comes in. H2 is a lightweight, in-memory database that runs right inside your Java application.

Think of it as a scratch pad for your data. It exists in memory while your app runs, and disappears when it stops. No installation, no configuration headaches. Just plug it in and start coding.

Configuring H2

Setting up H2 in Spring Boot is a breeze. Add the H2 dependency to your pom.xml and configure a few properties in application.properties. That's literally all it takes.

The key property is spring.datasource.url. For H2 in-memory mode, use jdbc:h2:mem:testdb. The database name after mem: can be anything you want. Spring Boot auto-configures everything else.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

H2 Console

H2 comes with a built-in web console. It's a browser-based tool where you can run SQL queries, view tables, and inspect your data. Think of it as phpMyAdmin but simpler and built right into your app.

Enable it by setting spring.h2.console.enabled=true. Then navigate to http://localhost:8080/h2-console while your app is running. Log in with the username and password from your properties file.

The console is incredibly useful for debugging. You can see exactly what data your app is storing, run test queries, and verify that your entities map correctly to the database schema.

Using H2 for Development

H2 is perfect for development and testing. It starts instantly, uses no disk space, and resets every time you restart your app. This means you always start with a clean slate.

You can also use it with Spring Boot's auto DDL generation. Set spring.jpa.hibernate.ddl-auto=update and Hibernate will create or modify tables based on your entities. When you're ready for production, swap H2 for MySQL or PostgreSQL.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is H2 Database?