Spring Boot: JdbcTemplate Update Query With Parameters Example


Step 1: Add the Spring JDBC dependency in your pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Step 2: Configure your database in the application.properties

spring.datasource.url=jdbc:mysql://localhost/prodDB
spring.datasource.username=prodUser
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Step 3: Create JDBCTemplete @Bean

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}

Step 3: Create Table in your Database & Insert few records

CREATE TABLE `employee` (
  `employeeId` int(5) NOT NULL,
  `employeeName` varchar(255) NOT NULL,
  `employeeDateOfBirth` date NOT NULL,
  `employeeDepartment` varchar(255) NOT NULL,
  `employeeJoiningDate` date NOT NULL,
  `employeeSalary` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
COMMIT;
insert into employee values(101,'Mike','2001-04-11','IT','2021-01-01',24000);

Step 4: Create @Repository Class with Update Query

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class AppRepository {

    private final JdbcTemplate jdbcTemplate;

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

Step 5: Create Update Query with Parameters

private String empName="Jose";
private String empDept="Finance";
private int empId=101;

public void updateRecord(String name, int age, long id) {
  String updateQuery = "UPDATE employee SET employeeName = ?, employeeDepartment = ? WHERE employeeId = ?";
  jdbcTemplate.update(updateQuery, empName, empDept, empId);
}

You can also make use of the named parameters instead of the ? in the query.

Example:
public void updateRecord(String name, int age, long id) {
   String updateQuery = "UPDATE employee SET employeeName = :empName, employeeDepartment = :empDept WHERE employeeId = :empId";
    
    Map<String, Object> params = new HashMap<>();
    params.put("empName", empName);
    params.put("employeeDepartment", empDept);
    params.put("employeeId", empId);
    jdbcTemplate.update(updateQuery, params);
}

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