How to create a Database Seeder in Spring Boot

Photo by Maksym Kaharlytskyi on Unsplash

Introduction

Spring Boot is an awesome Java web framework that is very comparable to Laravel web framework (in PHP). They both aim at making web application development fast and less rigorous for a developer.

Laravel has a cool feature that allows developers to create Seeders — i.e. default data to be inserted in the database.

In this article, we are going to see how to achieve the same thing in Spring Boot. The strategy thas we are using here is simple and straightforward : First, we will create a listener that listen to the application’s ContextRefreshEvent (1). The event is fired when the application has been totally bootstrapped, and all bean objects have been instantiated. Then we will use the Models and the repositories to persist default data into the database.

Now let’s implement this.

Implementation

First, let’s create a new class called DatabaseSeeder into a new package named seeders. It will be the root of our seeders.

Then we’ll need to create the event listener (1):

@EventListener
public void seed(ContextRefreshedEvent event) {
// Here goes the seeders
}

P.S. We must add the @Component to the DatabaseSeeder class.

Let’s assume that we need to seed the Users. So, we need a UsersSeeder :

@Autowired
UserRepository userRepository;
private void seedUsersTable() {
User user = new User();
user.setName("User's name");
user.setEmail("User's email");
userRepository.save(user);
}

And add the function to be executed in the event listener :

@EventListener
public void seed(ContextRefreshedEvent event) {
seedUsersTable();
}

Conclusion

We have seen how to seed data on application startup. We can use seeders to create default admin accounts, or any default data that we need to be theire for the application.

Thank you for reading.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store