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);
}
}

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!