#1
This guide shows how to configure Spring Boot to switch easily between H2 for local testing and PostgreSQL for production.

1. Add Dependencies

In pom.xml:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
</dependency>
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
</dependency>

2. Default Profile

In application.properties:
spring.profiles.active=dev
Set dev as the default profile.

3. H2 Configuration (Dev)

In application-dev.properties:
spring.datasource.url=jdbc:h2:mem:devdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop

4. PostgreSQL Configuration (Prod)

In application-prod.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update

5. Switching Profiles

Run with H2 (dev):
mvn spring-boot:run -Dspring-boot.run.profiles=dev
Run with PostgreSQL (prod):
mvn spring-boot:run -Dspring-boot.run.profiles=prod

6. Benefit

  • Use H2 for fast in-memory testing.
  • Use PostgreSQL for real-world production.
  • Easy switching with profiles.

image quote pre code