#1
This guide explains the difference between in-memory and file-based modes of the H2 database in Spring Boot projects.

1. In-Memory Mode

In-memory H2 stores data only while the application runs. When the app stops, data is lost. 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=create
spring.h2.console.enabled=true
Usage:
  • Great for testing.
  • No manual cleanup needed.
  • Fast performance.
  • Data not persisted after shutdown.

2. File-Based Mode

File-based H2 stores data on disk, making it persistent across restarts.
spring.datasource.url=jdbc:h2:file:./data/demoDB
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
Usage:
  • Great for small production apps or dev with persistence.
  • Data is retained after restart.
  • Slightly slower than memory mode.

3. Quick Example with Entity

import jakarta.persistence.*;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}
Repository:
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
}

4. Testing the Difference

  • Run the app in in-memory mode, add data, stop the app → data disappears.
  • Run in file-based mode, add data, restart → data still exists.

image quote pre code