This guide shows how to back up and restore H2 databases in Spring Boot projects for development and testing purposes.
1. Add H2 Dependency
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure H2 in File Mode
Use file-based mode so data persists and can be backed up:
spring.datasource.url=jdbc:h2:file:./data/demo
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
This stores the database in
./data/demo.mv.db.
3. Backup Database
H2 provides a SQL command for backup. Run this in your code or H2 console:
BACKUP TO './backup/demo.zip';
This creates a compressed backup file of your database.
4. Restore Database
To restore, copy the backup file to your database location:
unzip demo.zip -d ./data/
Or run in H2 console:
RUNSCRIPT FROM './backup/demo.zip';
5. Automate Backup in Spring Boot
@Component
public class BackupService {
@Autowired DataSource dataSource;
public void backup() throws Exception {
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement()) {
stmt.execute("BACKUP TO './backup/auto_demo.zip'");
}
}
}
image quote pre code