Database Initialization in Spring Boot

When working with Spring Boot and relational databases, initializing your database schema and loading seed data is a common requirement. Database Initialization in Spring Boot is easy using two files:

  • schema.sql: Used to create tables and structures
  • data.sql: Used to insert initial data

This post explains how to use them, how Spring Boot runs them, and best practices for both development and production. Lets see the techniques for Database Initialization in Spring Boot.

Database Initialization in Spring Boot

๐Ÿง  Why Use schema.sql and data.sql?

PurposeFileExample
Define database structureschema.sqlCREATE TABLE …
Insert seed or test datadata.sqlINSERT INTO …

These files are automatically executed by Spring Boot when the application starts.

๐Ÿ› ๏ธ How It Works

Spring Boot auto-detects and executes:

  • schema.sql: before Hibernate (DDL)
  • data.sql: after Hibernate (DML)

๐Ÿ”„ Execution Order:

  1. If Hibernate DDL is disabled, schema.sql creates the schema.
  2. Then, data.sql inserts data.
  3. Hibernate DDL can override schema if set.

๐Ÿ”ง Configuration Options

By default, Spring Boot will load these files from:

You can control execution using properties in application.properties:

๐Ÿ“ Directory Structure

โœ๏ธ Example: schema.sql

โœ๏ธ Example: data.sql

INSERT INTO users (name, email) VALUES (‘Alice’, ‘alice@example.com’);
INSERT INTO users (name, email) VALUES (‘Bob’, ‘bob@example.com’);

๐Ÿงช Verify with H2 Console

If using H2 for development, enable the console:

Visit http://localhost:8080/h2-console to browse your schema.

โš ๏ธ Common Pitfalls

IssueCause
Tables not createdHibernate overrides schema
Data not loadedspring.sql.init.mode not set to always
Syntax errorSQL dialect mismatch
Duplicate insertsdata.sql runs every time app restarts

๐Ÿง  When to Use schema.sql and data.sql

Use CaseRecommendation
Local developmentโœ… Use both for quick testing
Integration testingโœ… Use with embedded DB
ProductionโŒ Avoid. Use Liquibase/Flyway instead

๐Ÿ”„ Alternative: Hibernate Auto DDL

spring.jpa.hibernate.ddl-auto=create

Options:

  • none
  • create
  • create-drop
  • update
  • validate

Drawbacks:

  • Not suitable for production
  • Can cause data loss

๐Ÿš€ Best Practices

Best PracticeWhy
Use only for development or testNot safe for production
Place files in resources/Required for auto-detection
Add spring.sql.init.mode=alwaysEnsures consistent behavior
Use insert ... if not exists in data.sqlAvoids errors on rerun
For production, use Liquibase or FlywayHandles migrations safely

๐Ÿงน Summary

  • schema.sql: defines schema, runs before Hibernate
  • data.sql: loads initial data, runs after Hibernate
  • Configure with spring.sql.init.* properties
  • Great for testing, not suitable for production