How to Load Initial Data in Spring Boot Application

Quick Guide on Loading Initial Data with Spring Boot

If you are from a Laravel background, you will know how easy it is to load initial data into the database. In Spring Boot, the process is as simple as it is in the Laravel framework.

While using JPA, your entity would look something like this:

public class User {
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;
    @NotBlank(message = "Username is required")
    private String username;
    @NotEmpty(message = "Email is required")
    private String email;
    // Getters and setters
}Code language: PHP (php)

When you run your application, the table ‘user’ will be created.

Alternately, you can also create tables by writing entities schema in a file named schema.sql in the resources folder.

But there will come a situation when there is a need for some data in your table when you access your application. For example, an admin user data to let the admin do his/her task.

To do this typical task, create a file named data.sql in the resources folder and write an insert script. For example:

insert  into sa_user(id, email,username) values (1, 'foo','');
Code language: JavaScript (javascript)

Importantly, in your file customize data initialization mode as follows: (given that you’re using a database other than embedded DataSource)


Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top