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:
Hint: Same location as
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');
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
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!