Spring Boot
Initial Data
Data Loading
Application Setup
Java Programming

Spring Boot - Loading Initial Data

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Spring Boot is a powerful framework that simplifies the development of Java applications by providing a comprehensive set of functionalities out-of-the-box. Among these functionalities is the ability to easily load initial data into your application's database. This feature is crucial for setting up a consistent development environment, populating test data, or even prepping demo environments. In this article, we'll delve deeper into the ways Spring Boot can be used to load initial data, incorporating technical explanations and examples to enhance your understanding.

Loading Initial Data in Spring Boot

Spring Boot offers several methods to initialize and populate databases with initial data. Here are the primary techniques:

  1. Using data.sql Files
  2. Using CommandLineRunner or ApplicationRunner
  3. Using import.sql in Hibernate
  4. Using Spring Boot Flyway or Liquibase

1. Using data.sql Files

When using SQL-based databases, you can place a data.sql file in the src/main/resources directory. Spring Boot automatically executes this script during the application startup to populate data.

Example

Suppose you have a users table. Create a data.sql file like below:

sql
INSERT INTO users (id, name, email) VALUES (1, 'John Doe', '[email protected]');
INSERT INTO users (id, name, email) VALUES (2, 'Jane Smith', '[email protected]');

This script will be executed against the database when the application starts.

2. Using CommandLineRunner or ApplicationRunner

Another approach is to use either CommandLineRunner or ApplicationRunner, which are interfaces that allow code to execute after the application context is loaded.

Example

java
1import org.springframework.boot.CommandLineRunner;
2import org.springframework.stereotype.Component;
3import javax.transaction.Transactional;
4
5@Component
6public class DataInitializer implements CommandLineRunner {
7
8    @Autowired
9    private UserRepository userRepository;
10
11    @Override
12    @Transactional
13    public void run(String... args) throws Exception {
14        userRepository.save(new User(1L, "John Doe", "[email protected]"));
15        userRepository.save(new User(2L, "Jane Smith", "[email protected]"));
16    }
17}

3. Using import.sql in Hibernate

For those utilizing Hibernate, placing an import.sql file in the src/main/resources directory provides another method. It's a default Hibernate feature which is executed after the schema is created.

Example

Contents of import.sql:

sql
INSERT INTO users (id, name, email) VALUES (3, 'Bob Brown', '[email protected]');

4. Using Spring Boot Flyway or Liquibase

These are third-party database migration tools integrated with Spring Boot. They provide advanced capabilities for managing database migrations and also allow the initialization of schema and data.

Example Using Flyway

Create a file named V1__initial_data.sql in the db/migration directory:

sql
INSERT INTO users (id, name, email) VALUES (4, 'Alice White', '[email protected]');

Flyway will automatically run these scripts at startup.

Configuration and Considerations

  • Database Schema Creation: Ensure that the schema is created before loading data. This can be configured using the spring.jpa.hibernate.ddl-auto property. Options like create and update are useful during development but should be avoided in production.
  • Transaction Management: When using CommandLineRunner, it is crucial to manage transactions effectively to ensure that data persistence is consistent and reliable.
  • Environment-Specific Profiles: You might want different data for dev, test, and production environments. Spring Profiles can help you achieve this by creating environment-specific configurations and data sets.

Summary Table

MethodUse CaseAdvantagesDisadvantages
data.sqlSimple initial dataEasy to set upLimited to SQL-based databases
CommandLineRunner   ApplicationRunnerProgrammatically customizableGreater flexibility with Java logicRequires bootstrap coding
import.sqlHibernate usersAutomatically executed by HibernateDependent on Hibernate; limited flexibility
Flyway / LiquibaseComplex migrations   and data setupsAdvanced migration capabilities   with version controlAdditional setup and learning curve

Additional Details and Subtopics

Testing with Initial Data

In test environments, initial data loading helps in creating a repeatable and controlled setup. Use annotations like @Sql on test methods to specify scripts to be executed before or after tests:

java
1@Sql({"/test-data.sql"})
2public void testFindAllUsers() {
3    List<User> users = userService.findAll();
4    // assertions
5}

Handling Versioning and Multiple Environments

When using tools like Flyway or Liquibase, managing versioning becomes straightforward. Simply increment the version number in your migration scripts to ensure chronological execution.

Conclusion

Spring Boot provides a plethora of methods for loading initial data into databases, empowering developers to tailor their applications and environments to suit various needs. Whether opting for simpler data.sql scripts or more robust solutions like Flyway, the choice depends on the complexity and demands of your project. By understanding and leveraging these options, developers can streamline their development processes, ensure consistency, and maintain flexible environments.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.