Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 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');
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit 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!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Artisan
  • Location
    Nigeria
  • Education
    Delta State Polytechnic - Computer Science
  • Work
    Software Engineer - FullStack (Java, JavaScript) at Decagon Ins
  • Joined

More fromEmmanuel Ogbinaka

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp