Loading Initial Data with Spring Boot
Last Updated :
29 Apr, 2024
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", "[email protected]"));
userRepository.save(new User("Eswar", "[email protected]"));
}
}
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.
Similar Reads
Hot Reload with Spring Boot DevTools
Hot reloading allows developers to see changes made to their application in real-time without restarting the server. In Spring Boot, this is achieved through Spring Boot DevTools. This tool significantly enhances development by reducing the time required to see changes in the application.Hot Reload
3 min read
Spring Boot with H2 Database
H2 Database in Spring Boot is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some b
6 min read
Spring Boot - Spring Data JPA
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any java object directly into a database table. Usually, the name of the object being persisted become
6 min read
Spring Boot - Caching with Redis
Caching is a crucial optimization technique used to enhance the performance and scalability of web applications. It temporarily stores data in cache memory to reduce access time and load on backend systems. Redis (Remote Dictionary Server) is a popular open-source, in-memory data structure store use
7 min read
Pagination and Sorting with Spring Data JPA
Pagination and sorting are crucial features when dealing with large datasets in applications. They can help to break down into manageable chunks and provide a way to order the data according to specific criteria. In the Spring Boot application using Spring Data JPA, we can easily implement these fea
5 min read
Spring Security Integration with Spring Boot
Spring Security is a powerful and customizable authentication and access control framework for Java applications. It provides comprehensive security services for Java EE-based enterprise software applications. This article will integrate Spring Security with a Spring Boot application, covering confi
5 min read
Introduction to Spring Boot
Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
5 min read
Dynamic Query in Java Spring Boot with MongoDB
Most of todayâs applications require great flexibility regarding database querying. MongoDB provides an effective option for solving complex queries using this kind of storage for documents. Integrating it with Spring Boot makes things even smoother. In this article, we will look at how to create dy
4 min read
Spring Boot - File Handling
Spring Boot is a popular, open-source spring-based framework used to develop robust web applications and microservices. As it is built on top of Spring Framework it not only has all the features of Spring but also includes certain special features such as auto-configuration, health checks, etc. whic
5 min read
Spring Boot - @LoadBalanced Annotation with Example
The @LoadBalanced annotation creates an instance of created RestTemplate load-balanced. There is no code you need to write to make the RestTemplate load-balance HTTP request it sends to an internal microservice. The RestTemplate bean will be intercepted and auto-configured by Spring Cloud. In brief,
10 min read