In this example, we take a look at how to make use of NamedParameterJdbcTemplate to perform batch insert/update using JDBCTemplate in Spring Boot.
Make sure to create the Employee Pojo class.
import org.code2care.jdbctemplate.eg.jdbctemplateeg.entities.Employee;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
@Repository
public class JDBCTemplateRepo implements CommandLineRunner {
private final JdbcTemplate jdbcTemplate;
public JDBCTemplateRepo(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void batchInsertRecords(List<Employee> employees) {
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
String sql = "INSERT INTO employee (employeeId, employeeName, employeeDateOfBirth, employeeDepartment, employeeJoiningDate, employeeSalary) VALUES (:id, :name, :dob, :dept, :joinDate, :salary)";
SqlParameterSource[] batch = employees.stream()
.map(employee -> new MapSqlParameterSource()
.addValue("id", employee.getEmployeeId())
.addValue("name", employee.getEmployeeName())
.addValue("dob", Date.valueOf(employee.getEmployeeDateOfBirth()))
.addValue("dept", employee.getEmployeeDepartment())
.addValue("joinDate", Date.valueOf(employee.getEmployeeJoiningDate()))
.addValue("salary", employee.getEmployeeSalary()))
.toArray(SqlParameterSource[]::new);
namedParameterJdbcTemplate.batchUpdate(sql, batch);
}
@Override
public void run(String... args) throws Exception {
List<Employee> employees = Arrays.asList(
new Employee(101, "John Smith", LocalDate.of(1990, 5, 15), "HR", LocalDate.of(2020, 1, 1),"Chicago",5000),
new Employee(201, "Jane Doe", LocalDate.of(1995, 8, 25), "Sales", LocalDate.of(2019, 5, 1),"NYC", 6000),
new Employee(301, "Bob Mandy", LocalDate.of(1985, 10, 10), "Marketing", LocalDate.of(2021, 2, 1),"Austin", 7000)
);
batchInsertRecords(employees);
}
}
Result:
Other configurations
applications.propertiesspring.datasource.url=jdbc:mysql://localhost/jdbcTemplateDb
spring.datasource.username=root
spring.datasource.password=secure-password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.code2care.jdbctemplate.eg</groupId>
<artifactId>jdbctemplateeg</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jdbctemplateeg</name>
<description>Spring Boot JDBC Template Example</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
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
More Posts related to Java,
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
More Posts:
- Fix: error: Jupyter command `jupyter-nbconvert` not found [VSCode] - Python
- How to know the Version of Notepad App on Windows 11 - Windows-11
- remove div vertical scroll - Html
- [Solution] WslRegisterDistribution failed with error: 0x80370102 VM on Mac - Windows
- How to Pretty Print JSON in PHP - PHP
- Adding Custom ASCII Text Banner in Spring Boot Application - Java
- Python: Convert int to binary String - Python
- SharePoint List redirect user after submitting form NewForm.aspx - SharePoint