Open In App
Related Articles

Spring – NamedParameterJdbcTemplate

Improve Article
Save Article
Like Article

The Java Database Connectivity (JDBC API) provides universal data access from any data sources(including relational databases, spreadsheets & flat files). The JdbcTemplate is the most basic and classic approach for data access. The NamedParameterJdbcTemplate wraps the JdbcTemplate and allows the use of named parameters instead of the traditional JDBC ‘?’ placeholder.


In this example, we will insert student data(id, name, department) into our data source using named parameters. NamedParameterJdbcTemplate has several methods we will use execute() method for this example.

Syntax of execute() method of NamedParameterJdbcTemplate:

public T execute(String sql, Map map, PreparedStatementCallback psc)

For this tutorial, we will be using the following schema for the Student table.

Student(id INT, name VARCHAR(45), department VARCHAR(45))

Step By Step Implementation

Step 1: Create Table

In this step, we will create a Student table to store students’ information. For this tutorial, we will assume you have created the following table in your database.

id INT,
name VARCHAR(45),
department VARCHAR(45));

Step 2: Adding dependencies

In this step, we will add the maven dependencies to our application. Add the following dependencies to your pom.xml 



Step 3: Create a model class

Now, we will create a model class for our students. This class will have three-member variables id, name, and department. We will also define its getters and setters method along with the toString() method and constructors.


public class Student {
    // member variables
    private int id;
    private String name;
    private String department;
    public Student() {}
    // parameterized constructor
    public Student(int id, String name, String department) {
        super(); = id; = name;
        this.department = department;
    // getters and setters method
    public int getId() {
        return id;
    public void setId(int id) { = id;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getDepartment() {
        return department;
    public void setDepartment(String department) {
        this.department = department;
    // toString() method
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", department=" + department + "]";

Step 4: Create a StudentDao class

In this step, we will create a StudentDao class and define the insertStudentInfo() method and provide its definition to insert data in our data source.


import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.geeksforgeeks.model.Student;
public class StudentDao{
    // Defining NamedParameterJdbcTemplate as member variable in order
    // to use the execute() method of the NamedParameterJdbcTemplate's class
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    // Constructor
    public  StudentDao(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    // User defined method to insert query data in data source
    public void insertStudentInfo(Student student) {
        String sqlQuery = "INSERT INTO student VALUES(:id, :name, :department)";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", student.getId());
        map.put("name", student.getName());
        map.put("department", student.getDepartment());
        namedParameterJdbcTemplate.execute(sqlQuery, map, new PreparedStatementCallback() {
            public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                return ps.executeUpdate();

Step 5: Bean Configuration

In this step, we will create the spring configuration file and name it application-context.xml. We will configure our beans and use the factory-method attribute for bean creation. In order to make a connection to the database, we need the following information username, password, database connection, URL, and the driver class name.  All this information is contained in the DriverManagerDataSource class, it has the getConnection() method which returns a connection of java type. We are using the instance of NamedParameterJdbcTemplate in our StudentDao class and passing it using the constructor injection method.

Note: In application-context, you need to define the whole path of your dao class


<?xml version="1.0" encoding="UTF-8"?> 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
        <property name="url" value="jdbc:mysql://localhost:3306/student_db?autoReconnect=true&useSSL=false" /> 
        <property name="username" value="root" /> 
        <property name="password" value="root" /> 
    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
        <constructor-arg ref="dataSource"></constructor-arg
    <bean id="studentDao" class="com.geeksforgeeks.dao.StudentDao"
        <constructor-arg><ref bean="namedParameterJdbcTemplate"/></constructor-arg

Step 6: Creating Utilities Class

Now, we will create a Utility class for testing our application. For this create a new class and name it and add the following code to it.


import org.springframework.beans.factory.BeanFactory; 
import org.springframework.beans.factory.xml.XmlBeanFactory; 
import com.geeksforgeeks.dao.StudentDao;
import com.geeksforgeeks.model.Student; 
public class TestNamedParameterJdbcTemplate {
    public static void main(String[] agrs) {
         // Reading the application-context file using
         // class path of spring context xml file
         Resource resource = new ClassPathResource("application-context.xml"); 
         BeanFactory factory = new XmlBeanFactory(resource); 
         // Spring check the blueprint for studentDao bean
         // from application-context.xml file and return it
         StudentDao studentDao = (StudentDao)factory.getBean("studentDao"); 
         Student studentObj = new Student(1, "geek", "computer science department");

Step 7: Output

Now, we will run our application


Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated : 06 Feb, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials