Spring Boot: JDBCTemplate BatchUpdate Update Query Example


The batchUpdate() is a method provided by the JdbcTemplate class in Spring Boot that allows multiple SQL queries to be executed in a batch. It takes an SQL query string and a BatchPreparedStatementSetter object that specifies how to set the parameters for each query.

The batchUpdate() method then executes the SQL query for each set of parameters in a single round-trip to the database, improving performance by reducing the number of database calls.

This method is helpful when multiple queries need to be executed in a single transaction, or when a large number of queries need to be executed with minimal overhead.

import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;

@Repository
public class JDBCTemplateRepo implements CommandLineRunner {

    private final JdbcTemplate jdbcTemplate;

    public JDBCTemplateRepo(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void batchUpdateRecords(int[] employeeIds, int[] newSalaries) {
        String sql = "UPDATE employee SET employeeSalary = ? WHERE employeeId = ?";

        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setInt(1, newSalaries[i]);
                ps.setInt(2, employeeIds[i]);
            }

            @Override
            public int getBatchSize() {
                return employeeIds.length/2; //set per your batch
            }
        });
    }

    @Override
    public void run(String... args) throws Exception {
        int empIdArr[] = {101,201,301,404,505,606,707};
        int empSalaryArr[] = {1000,2000,3000,4000,5000,6000,7000};
        batchUpdateRecords(empIdArr,empSalaryArr);
    }
}
Updated records in database table

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap