DEV Community

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

Posted on

5

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!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay