AI Hints
Home›Spring Boot Tutorial›Why a Database, The H2 Database and What JPA Is
Spring Boot · Lesson 47 of 120

The H2 Database

A database inside your app.

⏱ 2 min read▶ Video at 1:02:56🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Installing a database server takes time. For learning, and for tests, there's a shortcut. H2 is a small database, that runs inside your Java app.

  • Servers take time to set up
  • A shortcut
  • H2 runs inside your app

H2 in a nutshell

H2 is a database, written in Java. In memory mode, it starts with your app, and its data vanishes when the app stops. That's perfect for learning, and testing. Later, you can switch to PostgreSQL, or MySQL, by changing a few settings.

keyvalue
H2a Java database
Memory modestarts and stops with the app
Great forlearning and tests
LaterPostgreSQL or MySQL

Settings

In Spring Initializr, we add two dependencies, Spring Data JPA, and the H2 database. The data source URL says, an in memory H2 database, called bookshop. Sa is the default user name. And the H2 console gives you a web page, at slash h2 console, to look inside.

application.propertiesini
spring.datasource.url=jdbc:h2:mem:bookshop
spring.datasource.username=sa
spring.h2.console.enabled=true

Real SQL on H2

Spring Boot sees H2, and gives us a ready data source, and a Jdbc Template bean. Jdbc Template runs SQL for us. At startup, this runner creates a table, inserts two rows, and selects them. Then it selects only the cheap titles. Run it. Each row comes back as a map, of column to value. And only Dune costs less than ten.

SqlDemo.javajava
@Component
public class SqlDemo implements CommandLineRunner {

    private final JdbcTemplate jdbc;

    public SqlDemo(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    @Override
    public void run(String... args) {
        jdbc.execute("CREATE TABLE book (id INT PRIMARY KEY, title VARCHAR(100),"
                     + " price DECIMAL(6,2))");
        jdbc.update("INSERT INTO book VALUES (1, 'Dune', 9.99), (2, 'Circe', 10.99)");
        jdbc.queryForList("SELECT * FROM book").forEach(System.out::println);
        System.out.println("Cheap books: " + jdbc.queryForList(
            "SELECT title FROM book WHERE price < 10", String.class));
    }
}
Output
{ID=1, TITLE=Dune, PRICE=9.99}
{ID=2, TITLE=Circe, PRICE=10.99}
Cheap books: [Dune]

Summary

H2 is a Java database that runs inside your app, in memory. Spring Boot sets it up for you. Next, JPA, which saves us from writing SQL by hand.

Key takeaways
  • H2 in memory
  • Auto-configured
  • JdbcTemplate runs SQL
Next up: What JPA Is — objects instead of SQL