Loading Initial Data with Spring Boot

Loading initial data into a Spring Boot application is a common requirement for seeding the database with predefined data. This data could include reference data, default settings, or simple records to populate the application upon startup.

The main concept involves using Spring Boot’s data initialization feature to load initial data into the database during application startup. This can be achieved using various methods such as SQL scripts, data import files, or Java-based initialization of the Spring application.

Key Terminologies:

  • Data Source: A data source represents the connection to the database. In Spring Boot, we typically configure data sources in the application.properties file.
  • Data Loader: It is a component responsible for loading initial data into the application when it starts up. This can include inserting default records into the database.
  • CommandLineRunner: CommandLineRunner is a functional interface provided by Spring Boot. We can implement this interface to execute custom code when the application starts up. This is often used for loading initial data or performing other startup tasks.

Step-by-step Implementation to Load Initial Data with Spring Boot

Step 1: Create a spring project using spring initializer and add the below dependencies to the project.

Dependencies:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver
  • Lombok

After creating the Spring project, the file structure resembles the image below.


Step 2: Open the application.properties file and put the below code for the server port and MySQL database configuration to the project.

spring.application.name=intial-data-demo

spring.datasource.url=jdbc:mysql://localhost:3306/example
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update


Step 3: Create the User model class

Go to src > org.example.intialdatademo > model > User and put the below code.

Java
package org.example.intialdatademo.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    public User(String str1, String str2) {
    }
}


Step 4: Create the UserRepository class

Go to src > org.example.intialdatademo > repository > UserRepository and put the below code.

Java
package org.example.intialdatademo.repository;

import org.example.intialdatademo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}


Step 5: Create the DataLoader class

Go to src > org.example.intialdatademo > config > DataLoader and put the below code.

Java
package org.example.intialdatademo.config;

import org.example.intialdatademo.model.User;
import org.example.intialdatademo.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DataLoader implements CommandLineRunner {

    private final UserRepository userRepository;

    public DataLoader(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        // Load initial data into the database
        userRepository.save(new User("Raj Kumar", "rajkumar@example.com"));
        userRepository.save(new User("Eswar", "eswae@example.com"));
    }
}


Step 6: Create the UserController class

Go to src > org.example.intialdatademo > controller > UserController and put the below code.

Java
package org.example.intialdatademo.controller;

import org.example.intialdatademo.model.User;
import org.example.intialdatademo.repository.UserRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/users")
    public List<User> getUsers() {
        return userRepository.findAll();
    }
}


Step 7: Open the default main class (No changes are required).

Java
package org.example.intialdatademo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class IntialDataDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(IntialDataDemoApplication.class, args);
    }

}


Step 8: Run the application

Once the Spring project is completed and successfully run as a Spring application, it will start running on port 8080.


Step 9: Testing the API

GET http://localhost:8080/users

Output:

The above spring boot example demonstrates the simple application structure with the capability to the load initial data into the database upon the application startup. The User entity represents the data model and the DataLoader class is the responisible for the seeding initial data using the Spring Boot’s CommandLineRunner interface.



Contact Us