The Wayback Machine - https://web.archive.org/web/20240906182021/https://www.geeksforgeeks.org/spring-namedparameterjdbctemplate/
Open In App

Spring – NamedParameterJdbcTemplate

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Example

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.

CREATE TABLE STUDENT(
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 

XML




<dependencies>
   
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.16</version>
        </dependency>
         
        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.0.8.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
         
</dependencies>


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.

Java




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();
        this.id = id;
        this.name = name;
        this.department = department;
    }
   
    // getters and setters method
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
     
    // toString() method
    @Override
    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.

Java




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




<?xml version="1.0" encoding="UTF-8"?> 
<beans 
                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
   
    <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> 
       
    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> 
        <constructor-arg ref="dataSource"></constructor-arg> 
    </bean> 
   
    <bean id="studentDao" class="com.geeksforgeeks.dao.StudentDao"> 
        <constructor-arg><ref bean="namedParameterJdbcTemplate"/></constructor-arg> 
    </bean>  
   
</beans>


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 TestNamedParameterJdbcTemplate.java and add the following code to it.

Java




import org.springframework.beans.factory.BeanFactory; 
import org.springframework.beans.factory.xml.XmlBeanFactory; 
import org.springframework.core.io.ClassPathResource; 
import org.springframework.core.io.Resource;
 
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");
         studentDao.insertStudentInfo(studentObj);
         System.out.println(studentObj);
    }
 
}


Step 7: Output

Now, we will run our application

Output



Previous Article
Next Article

Similar Reads

Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Controller, and seamlessly handles the application in
3 min read
How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
Spring - Add User Name and Password in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
3 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt
3 min read
Spring - Add Roles in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
4 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using maps. In this article, we will see how to set up a Spring
5 min read
Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
We will be running the SQL scripts with Spring JDBC +JPA + HSQLDB. These scripts are used to perform SQL commands at the time of application start. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. JPA is just a specification that faci
3 min read
How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?
For the sample project, below mentioned tools got used Java 8Eclipse IDE for developmentHibernate ORM, Spring framework with Spring Data JPAMySQL database, MySQL Connector Java as JDBC driver.Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven Project Structure: As this is getting prepared as a maven project, all dependencies are s
4 min read
How to Generate a New Spring Cloud Project in Spring Initializr?
Spring Initializr is a Web-based tool that generates the Spring Boot project structure. The spelling mistake in initializr is inspired by initializr. Modern IDEs have integrated Spring Initializr which provides the initial project structure. It is very easy for developers to select the necessary configuration for their projects. The Spring Initiali
2 min read
Spring - Integration of Spring 4, Struts 2, and Hibernate
In modern Java web application development, integrating different frameworks is a common requirement to leverage the strengths of each framework. Spring, Struts, and Hibernate are three popular frameworks that can work together seamlessly to build robust and scalable applications. In this article, we will explore how to integrate Spring 4, Struts 2
4 min read
Java Spring Boot Microservices – Integration of Eureka and Spring Cloud Gateway
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
5 min read
What's New in Spring 6 and Spring Boot 3?
Spring and Spring Boot are two of the most popular Java frameworks used by developers worldwide. The Spring team is continuously working on improving and enhancing the frameworks with each new major release. Spring 6 and Spring Boot 3 are expected to bring in significant new features and changes that will further boost development with these techno
5 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorizatio
2 min read
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
Spring Tool Suite (STS) is a Java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for your favorite coding environment. Largely rebuilt
2 min read
Java Spring Boot Microservices - Integration of Eureka, Feign & Spring Cloud Load Balancer
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
13 min read
Java Spring Boot Microservices - Client Side Load Balancing with Spring Cloud LoadBalancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
12 min read
Difference between Spring and Spring Boot
Spring Spring is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier compared to classic Java frameworks and Appl
4 min read
Difference Between Spring MVC and Spring WebFlux
Spring MVCSpring MVC Framework takes on the Model-View-Controller design pattern, which moves around the Dispatcher Servlet, also called the Front Controller. With the help of annotations like @Controller and @RequestMapping, the by-default handler becomes a robust(strong) tool with a diverse set of handling ways. This kind of dynamic kind of featu
5 min read
Spring Data JPA vs Spring JDBC Template
In this article, we will learn about the difference between Spring Data JPA vs Spring JDBC Template. Spring Data JPATo implement JPA-based repositories, Spring Data JPA, a piece of the Spring Data family, takes out the complexity. With the help of spring data JPA the process of creating Spring-powered applications that support data access technolog
5 min read
Spring AOP vs Spring IOC
Spring AOPAspect Oriented Programming i.e. AOP, is another way to program a structure, similar to Object-oriented Programming (OOP). Object-oriented Programming (OOP) completely depends upon classes as the main modular unit, whereas Aspect Oriented Programming (AOP) moves the main idea to aspects. Aspects are the essential element that allows probl
4 min read
Spring MVC vs Spring Web Flux: Top Differences
For creating Java-based projects and applications, developers usually have to choose between Spring MVC and Spring WebFlux when using the Spring framework to create web apps. To pick the best framework for their project, developers need to know how each one is different and what features they have. Each framework has its own benefits compared to th
11 min read
Spring Cloud Vs Spring Boot Actuator
Spring CloudSpring Cloud's main purpose is to give tools and services for managing and making distributed systems, especially in a microservices architecture. The developer wants to speed up the process of building patterns in distributed systems, these tools can fulfill their requirement. They include almost all from the management of configuratio
5 min read
Configuring Multiple Spring Batch Jobs in a Spring Boot Application
Spring Batch serves as a robust framework within the Spring ecosystem, specifically tailored for managing batch processing tasks efficiently. It's designed to tackle big data jobs efficiently and comes with handy tools to make batch application development a breeze. In the context of a Spring Boot application, setting up multiple Spring Batch jobs
10 min read