Batch updates + Prepared Statement with Spring Boot 3 + JDBC

This tutorial covers snippets and not complete code. It is assumed that you already have a downloaded and setup your Spring Boot 3+ JDBC project using Spring Initializr in your IDE.

We extensively covered how to setup up Spring Boot + Maven + JDBC + MySQL database in this tutorial:

Below is a code snippet to perform batch update with plain JDBC.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

public class BatchUpdateRunner implements CommandLineRunner {

    private JdbcTemplate jdbcTemplate;

    public void run(String... args) throws Exception {

        List<InsuranceCompanies> companies = new ArrayList<>();
        companies.add(new InsuranceCompanies("MetLife", 49000, "New York"));
        companies.add(new InsuranceCompanies("Prudential Financial", 50527, "Newark"));
        companies.add(new InsuranceCompanies("New York Life Insurance", 11902, "New York"));
        companies.add(new InsuranceCompanies("Aflac", 11128, "Columbus"));
        companies.add(new InsuranceCompanies("Liberty Mutual", 45000, "Boston"));

        // Prepare the SQL insert statement
        String sql = "INSERT INTO insurance_companies (company_name, headcount_2020, head_office_location) VALUES (?, ?, ?)";

        List<Object[]> batchArgs = new ArrayList<>();
        for (InsuranceCompanies company : companies) {
            Object[] params = {company.getCompanyName(), company.getHeadcount2020(), company.getHeadOfficeLocation()};

        jdbcTemplate.batchUpdate(sql, batchArgs); //batch Update
Records inserted using Spring Boot and JDBC Batch Update
You can find the table structure and the POJO details in below tutorial where we have covered CRUD operations in detail.



Have Questions? Post them here!