This guide shows how to migrate a
Spring Boot project from
H2 to a production database such as MySQL or PostgreSQL.
1. Current Setup with 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
2. Replace H2 with Production Database
For
MySQL, update configuration:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
For
PostgreSQL:
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
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
3. Update Dependencies
Add database driver in
pom.xml
:
MySQL:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
PostgreSQL:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
4. Verify Schema
Ensure entities map correctly. Use
spring.jpa.hibernate.ddl-auto=validate
to avoid accidental schema changes.
5. Test the Migration
Run the app and confirm that data is stored in the production DB instead of H2.
image quote pre code