Spring JDBC

NamedParameterJdbcTemplate in Spring with Example

The NamedParameterJdbcTemplate class helps you specify the named parameters instead of classic placeholder(‘?’) argument. Named parameters improves readability and are easier to maintain.

The NamedParameterJdbcTemplate provide better approach than JdbcTemplate ,where multiple parameters are in use for an SQL statement. It eliminated need of traditional JDBC “?” and provide named parameters. It is easy to use and provide better documentation. It functionality is similar to JdbcTemplate except it incorporate named parameters instead of “?” placeholder.

In JdbcTemplate, SQL parameters are represented by a special placeholder “?” symbol and bind it by position. The problem is whenever the order of parameter is changed, you have to change the parameters bindings as well, it’s error prone and cumbersome to maintain it.

 

In additional, the named parameters are only support in SimpleJdbcTemplate and NamedParameterJdbcTemplate.

EmpDao.java

package com.dineshonjava.sdnext.dao;

import java.util.List;

import com.dineshonjava.sdnext.domain.Employee;

/**
 * @author Dinesh Rajput
 *
 */
public interface EmpDao {
 
 /** 
  * This is the method to be used to create
  * a record in the Employee table.
  */
 void create(String name, Integer age, Long salary);
 /** 
  * This is the method to be used to list down
  * a record from the Employee table corresponding
  * to a passed Employee id.
  */
 Employee getEmployee(Integer empid);
 /** 
  * This is the method to be used to list down
  * all the records from the Employee table.
  */
 List listEmployees();
 /** 
  * This is the method to be used to delete
  * a record from the Employee table corresponding
  * to a passed Employee id.
  */
 void delete(Integer empid);
 /** 
  * This is the method to be used to update
  * a record into the Employee table.
  */
 void update(Integer empid, Integer age);
}

EmployeeDaoImpl.java

package com.dineshonjava.sdnext.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Component;

import com.dineshonjava.sdnext.dao.EmpDao;
import com.dineshonjava.sdnext.domain.Employee;
import com.dineshonjava.sdnext.jdbc.utils.EmployeeMapper;

/**
 * @author Dinesh Rajput
 *
 */
@Component
public class EmployeeDaoImpl implements EmpDao {
 @Autowired
 private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
 
 /**
  * @param namedParameterJdbcTemplate the namedParameterJdbcTemplate to set
  */
 public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
  this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
 }

@Override
public void create(String name, Integer age, Long salary) {
      String SQL = "INSERT INTO Employee (name, age, salary) VALUES (:name, :age, :salary)";
      Map namedParameters = new HashMap();   
      namedParameters.put("name", name);   
      namedParameters.put("age", age);
      namedParameters.put("salary", salary);
      namedParameterJdbcTemplate.update(SQL, namedParameters);
System.out.println("Created Record Name = " + name + " Age = " + age+ " Salary = " + salary);
}

@Override
public Employee getEmployee(Integer empid) {
   String SQL = "SELECT * FROM Employee WHERE empid = :empid";
   SqlParameterSource namedParameters = new MapSqlParameterSource("empid", Integer.valueOf(empid));
Employee employee = (Employee) namedParameterJdbcTemplate.queryForObject(SQL, namedParameters, new EmployeeMapper());
 return employee;
}

@Override
public List listEmployees() {
   String SQL = "SELECT * FROM Employee";
   List employees = (List) namedParameterJdbcTemplate.query(SQL, new EmployeeMapper());
     return employees;
}

@Override
public void delete(Integer empid) {
  String SQL = "DELETE FROM Employee WHERE empid = :empid";
  SqlParameterSource namedParameters = new MapSqlParameterSource("empid", Integer.valueOf(empid));
  namedParameterJdbcTemplate.update(SQL, namedParameters);
  System.out.println("Deleted Record with EMPID = " + empid );
}

@Override
public void update(Integer empid, Integer age) {
  String SQL = "UPDATE Employee SET age = :age WHERE empid = :empid";
  SqlParameterSource namedParameters = new MapSqlParameterSource();
  namedParameters.addValue("age", age);
  namedParameters.addValue("empid", empid);
  namedParameterJdbcTemplate.update(SQL, namedParameters);
 System.out.println("Updated Record with EMPID = " + empid );
 }
}

EmployeeMapper.java

package com.dineshonjava.sdnext.jdbc.utils;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.dineshonjava.sdnext.domain.Employee;

/**
 * @author Dinesh Rajput
 *
 */
public class EmployeeMapper implements RowMapper {  
 public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {  
  Employee employee = new Employee();  
  employee.setEmpid(rs.getInt("empid"));  
  employee.setName(rs.getString("name"));  
  employee.setAge(rs.getInt("age"));  
  employee.setSalary(rs.getLong("salary"));  
  return employee;  
 }  
}  

Spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago