DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis

Trending

  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty
  • Spring AI on Local LLMs
  • How an AI Software Factory Works: From Developer Intent to Production
  • GenAI Security Gateway: An End-to-End Architecture

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. How to Create a Database Seeder in Spring Boot

How to Create a Database Seeder in Spring Boot

Learn how to seed the database on application startup. Seeders can help you create default admin accounts or other default data required by your application.

By 
Seun Matt
DZone Core CORE ·
Jul. 22, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
35.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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 who 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 listens 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.

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();
}

Creating the Database Seeder

So far, we have registered an event listener and 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 auto-wired 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 = \"[email protected]\" 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("[email protected]");
             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 can be found here.

Spring Framework Spring Boot Database Web application

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook