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.

Implementation

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

@EventListener
public void seed(ContextRefreshedEvent event) {
// Here goes the seeders
}
@Autowired
UserRepository userRepository;
private void seedUsersTable() {
User user = new User();
user.setName("User's name");
user.setEmail("User's email");
userRepository.save(user);
}
@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.

Developer @AE | Fullstack Dev