Spring NamedParameterJdbcTemplate example

In this post , we are going to see about Spring NamedParameterJdbcTemplate. In previous post, we have already seen Spring JdbcTemplate example. NamedParameterJdbcTemplate is used to pass named parameter instead of ? in case of JdbcTemplate.
It makes code more readable and maintainable. Lets say you have 10 parameters and you have to use 10 ? to represent parameters and pass it in same sequence in object[] array but with the help of NamedParameterJdbcTemplate, it is very easy to specify parameters.
Lets compare code for JdbcTemplate and NamedParameterJdbcTemplate :

JdbcTemplate :

NamedParameterJdbcTemplate :

As you can see, we have use :{paramterName} for passing paramters instead of ? .

Example:

Lets understand with the help of simple example:
Create Country table in mysql database with following code:

We will you use Country table for querying and updating values in database. Lets first create our bean class Country.java

Create a DAO classed CountryDAO.java which will have all methods for database operations.

Create DAO implementation of above interface using normal JDBC APIs.

Create applicationcontext.xml as below

Configure datasource basaed on your connection details, datasource bean will be [autowired](https://java2blog.com/autowired-annotation-in-spring/ “autowired”) in CountryDAOImpl.
Create Main class named SpringApplicationMain.java as below

When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *