Provide Initial Default Data for Models in Spring Boot

When developing a Spring Boot application, you often encounter situations where you need to provide initial data to your models or entities. This initial data could be necessary for testing purposes, database seeding, or simply populating your application with default values. In this blog, we’ll explore various approaches to provide initial data for models in a Spring Boot application, along with code examples to illustrate each method.

1. Using Data SQL Scripts:

One of the simplest ways to provide initial data is by using data SQL scripts. Spring Boot allows you to define SQL scripts that run on startup to populate your database with the required data. To use this approach, follow these steps:

Step 1: Create a SQL file (e.g., data.sql) in the src/main/resources directory of your project.

Step 2: Write SQL statements in the data.sql file to insert the initial data into your model’s table.

Example data.sql:

INSERT INTO products (id, name, price) VALUES (1, 'Product A', 25.0);
INSERT INTO products (id, name, price) VALUES (2, 'Product B', 30.0);

To ensure the successful execution of the data.sql script during application startup, please follow these steps:

  1. Update Initialization Mode: Set the spring.sql.init.mode property to always in your application.properties or application.yml file. This ensures that the SQL scripts, including data.sql, are executed every time the application starts.
   spring.sql.init.mode=always
  1. Enable Deferred DataSource Initialization: To avoid conflicts during initialization, enable deferred DataSource initialization by setting spring.jpa.defer-datasource-initialization to true.
   spring.jpa.defer-datasource-initialization=true
  1. Verify DataSource Configuration: Make sure your DataSource configuration, including URL, username, and password, is correctly set in the application.properties or application.yml file.
   spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
   spring.datasource.username=your_database_username
   spring.datasource.password=your_database_password
  1. Place data.sql in Resources: Ensure that your data.sql script is located in the src/main/resources directory of your project.

After implementing these changes, restart your Spring Boot application. The data.sql script should now be executed during application startup, and your database should be populated with the sample data.

2. Using Spring Data JPA and CommandLineRunner:

If you are using Spring Data JPA, you can leverage the CommandLineRunner interface to execute code on application startup. This approach allows you to use Java code to create and populate model entities programmmatically.

Step 1: Implement the CommandLineRunner interface and override the run method.

Step 2: Use Spring Data JPA to persist the initial data into the database.

Example:

@Component
public class InitialDataLoader implements CommandLineRunner {

    private final ProductRepository productRepository;

    @Autowired
    public InitialDataLoader(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @Override
    public void run(String... args) {
        Product productA = new Product("Product A", 25.0);
        Product productB = new Product("Product B", 30.0);

        productRepository.saveAll(List.of(productA, productB));
    }
}

3. Using Data Seeder Library:

For more complex scenarios where you need to manage and load large sets of initial data, you can use external libraries like “Data Seeder.” Data Seeder is a popular library that allows you to define data seeders using Java classes or YAML files, providing better organization and maintenance for your initial data.

Step 1: Add the Data Seeder library to your project’s dependencies.

Get Maven or Graddle Dependency Code from https://mvnrepository.com/artifact/com.github.timols/seeder/0.1.0

Step 2: Create seeders to define and load initial data for your models.

Example (using Data Seeder):

@Component
public class ProductDataSeeder implements DataSeeder {

    private final ProductRepository productRepository;

    @Autowired
    public ProductDataSeeder(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @Override
    public void run() {
        Product productA = new Product("Product A", 25.0);
        Product productB = new Product("Product B", 30.0);

        productRepository.saveAll(List.of(productA, productB));
    }
}

Conclusion

Providing initial data for models in your SpringBoot application is crucial for various purposes, and Spring Boot offers multiple ways to accomplish this task. Whether you choose to use data SQL scripts, Spring Data JPA with CommandLineRunner, or an external library like Data Seeder, you now have the knowledge and examples to get started. Select the approach that best fits your project’s requirements and enjoy the benefits of having initial data readily available for your models. Happy coding!

Read our Blogs on How to Use MySQLPostgresMongoDBRedis in Django