Java, Software Development, Spring, Spring Boot

Spring Boot – Loading Data Using a SQL Script

This post demonstrates how to load data from an SQL script for a particular database platform. This post is ideal for the development stage when you need some seed data to fill in existing database tables.

Spring Boot Application

Let’s create a new Spring Boot Application using IntelliJ (optional) and Spring Initialzr (or http://start.spring.io/).

Step 1: Create a New Project

Choose Spring Initialzr. Then, click Next.

Step 2: Provide project information

Then, provide some information for Maven.

Step 3: Choose JPA and H2

Then, choose JPA and H2.

Step 4: Save the new project

Step 5: Create an entity class

The following class represents the Person table in our H2 database.

Step 5: Modify application.properties

Update the application.properties file with the following value.

With this setting, Spring will look for an SQL script data-h2.sql in the src/main/java/resources/ directory. Then, it will execute all the SQL statements in the script.

If we had spring.datasource.platform=hsqldb, Spring will try to load an SQL script named data-hsqldb.sql

For more information, please visit https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

Step 6: Unit Test

Lastly, we test our codes.

Download the codes

https://github.com/Turreta/Spring-Boot-Loading-Data-Using-a-SQL-Script

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like