This guide shows how to use
schema.sql and
data.sql for automatic
database initialization in
Spring Boot with H2.
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>
2. Configure H2
In
application.properties:
spring.datasource.url=jdbc:h2:mem:initdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=none
spring.h2.console.enabled=true
Set
ddl-auto=none to ensure Hibernate does not override your schema.
3. Create Schema.sql
In
src/main/resources/schema.sql:
CREATE TABLE employee (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
role VARCHAR(50)
);
4. Create Data.sql
In
src/main/resources/data.sql:
INSERT INTO employee (name, role) VALUES ('Alice', 'Developer');
INSERT INTO employee (name, role) VALUES ('Bob', 'Tester');
5. Access Database
Start the app and open the H2 console at:
http://localhost:8080/h2-console
Use JDBC URL:
jdbc:h2:mem:initdb to view tables and data.
6. Verify
Run query:
SELECT * FROM employee;
You will see
Alice and
Bob records preloaded into the database.
image quote pre code