#1
This guide shows how to set up H2 database in a Spring Boot project for testing or lightweight development with minimal configuration.

1. Add Dependency

In pom.xml:
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>

2. Configure H2

In application.properties:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
This sets H2 to in-memory mode and enables the web console at /h2-console.

3. Create Entity

import jakarta.persistence.*;

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
}

4. Repository

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {
}

5. Controller

import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    private final BookRepository repo;

    public BookController(BookRepository repo) {
        this.repo = repo;
    }

    @PostMapping
    public Book add(@RequestBody Book book) {
        return repo.save(book);
    }

    @GetMapping
    public List<Book> all() {
        return repo.findAll();
    }
}

6. Run and Test

Start the app:
mvn spring-boot:run
  • Open /h2-console in browser.
  • JDBC URL: jdbc:h2:mem:testdb.
  • Query and check stored data.

image quote pre code