How to Create a Database Seeder in Spring Boot

Seun Matt
3 min readAug 7, 2017

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.

I am a Java lover that courts Laravel due to professional requirements. Laravel framework has a feature that lets you create database seeders — i.e. default data to be inserted into the database during application installation.

Let’s set out to achieve the same thing in Spring Boot. The technique we will use is simple and straightforward: first, we will create a listener that listen to the application’s ContextRefreshEvent.

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 configured repositories to persist default data into the database.

2. Registering the Event Listener

In Spring Boot, we can register an event listener by just declaring that event as a parameter of a method and then annotating the method with @EventListener During application startup, Spring Boot will find the event listener and register it automatically:

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

3. Creating the Database Seeder

So far we have registered an event listener, and also we have called different methods to seed the database accordingly. One crucial advantage of running the seeders when the ContextRefreshEvent is fired is that, we get access to all autowired beans in the application — including models and repositories.

In the seedUsersTable(), and other seeder methods, we first check if the data exists already by trying to select it using SQL. If the data does not exist, we use the model and repository to persist the data else we just log a message.

private void seedUsersTable() {
String sql = "SELECT username, email FROM users U WHERE U.username = \"admin\" OR U.email = \"test@test.com\" LIMIT 1";
List<User> u = jdbcTemplate.query(sql, (resultSet, rowNum) -> null);
if(u == null || u.size() <= 0) {
User user = new User();
user.setName("Spring Blog");
user.setUsername("admin");
user.setEmail("test@test.com");
user.setPassword(new BCryptPasswordEncoder().encode("test123"));
user.setRole(Roles.SUPER_ADMIN.toString());
user.setBanned(false);
user.setConfirmEmail(true);
userRepository.save(user);
logger.info("Users Seeded");
} else {
logger.info("Users Seeding Not Required");
}
}

Conclusion

We have seen how to seed the database on application startup. We can use seeders to create default admin accounts, or other default data required by our application.

The complete source code is part of this Open Source Project which is a complete and full-featured blog web application built in Java using the Spring Boot web framework. Visit the repo and fork (or star) it for personal use.

Thank you for reading, kindly recommend this article by clicking the heart icon. Also share it on twitter and Facebook. Got questions? leave them in the response section.

Have you heard of PalCrib? It’s a new social media app that I am working on. If you love my writings, you’ll definitely enjoy the app. Download it now from Google PlayStore and let me know what you think

Originally published at dzone.com

--

--