DEV Community

Cover image for Loading Initial Data with Spring Boot
Emmanuel Ogbinaka
Emmanuel Ogbinaka

Posted on

Loading Initial Data with Spring Boot

With SpringBoot + Hibernate we can easily manage our database. By default, all classes marked with the @Entity annotation in our packages are used to create tables automatically.

Well, there are times we need more fine-grained control over the database alterations according to our requirements.
In this post I'll be sharing lights on one of those scenarios: Auto-populating or loading initial values into our tables.

SpringBoot has some reservations for situations as this. We make use of the data.sql file in Spring to actualise this.

This file should be saved in the directory:
src/main/resources/

Hint: Same location as application.properties file.

When we run the project with this file on the resources directory, Spring will pick it up and use it for populating the database.

As an example, we can decide to load initial values for the Role entity as follows:

INSERT INTO Role (name) VALUES ('USER');
INSERT INTO Role (name) VALUES ('ADMIN');
Enter fullscreen mode Exit fullscreen mode

When you start your application, spring will attempt to load these data into the Role table which at this time does not exist which will cause the program to fail, so we need to add the following config to application.properties file

spring.jpa.defer-datasource-initialization=true
Enter fullscreen mode Exit fullscreen mode

This tells spring to delay the data initialisation process. Now start your spring application, and you should be able to see the values 'USER' & 'ADMIN' in the Role table.

Hope you find this helpful. You can leave a comment to contribute. Thanks!

Oldest comments (0)