
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 thedata.sql
file in Spring to actualise this.
This file should be saved in the directory:
src/main/resources/
Hint: Same location asapplication.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 theRole
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 theRole
table which at this time does not exist which will cause the program to fail, so we need to add the following config toapplication.properties
file
spring.jpa.defer-datasource-initialization=true
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!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse