DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Resolving Parameter Sensitivity With Parameter Sensitive Plan Optimization in SQL Server 2022
  • Comparing Managed Postgres Options on The Azure Marketplace
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Ultimate Guide to Code Formatting: Prettier vs ESLint vs Biome
  • Proactive Security in Distributed Systems: A Developer’s Approach
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Specify Named Parameters Using the NamedParameterJdbcTemplate

How to Specify Named Parameters Using the NamedParameterJdbcTemplate

In this article, we will be learning how to use NamedParameterJdbcTemplate to pass named parameter.

By 
Rajesh Bhojwani user avatar
Rajesh Bhojwani
·
Jan. 28, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
96.2K Views

Join the DZone community and get the full member experience.

Join For Free

Overview

Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC API but eliminates a lot of problems of JDBC API. It helps to avoid writing boilerplate code for such as creating the connection, statement, closing resultset, connection, etc.. 

With JdbcTemple, we generally do pass the parameter values with "?" (question mark). However, it is going to introduce the SQL injection problem. So, Spring provides another way to insert data by the named parameter. In that way, we use names instead of "?". So it is better to remember the data for the column. This can be done using NamedParameterJdbcTemplate.

In this article, we will be learning how to use NamedParameterJdbcTemplate to pass named parameter.

Prerequisites

  • JDK 1.8

  • Spring-Boot Basic Knowledge

  • Gradle

  • Any IDE (Eclipse, VSD)

Gradle Dependency

This project needs a standard spring-boot-starter-web along with spring-boot-starter-jdbc and h2 database driver. I am using spring-boot version springBootVersion = '2.1.2.RELEASE' for this exercise:

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

Configuration

We are using H2 as the database. And H2 provides a web interface called H2 Console to see the data. Let’s enable h2 console in the application.properties

/src/main/resources/application.properties:

# Enabling H2 Console
spring.h2.console.enabled=true

server.port=8100

Also, We have configured the port as 8100 for this application. We will see how to use the H2 Console later. For now, let's put other required code.

Domain

Let's create a domain class User. We will use this class to map with DB table USERS and insert each field of this object to this table:

public class User {

    private int id;
    private String name;
    private String address;
    private String email;
  // standard setters and getters
}

DAO

Now, let's create a DAO interface UserDao which defines what all methods need to be implemented:

public interface UserDao {
    public User create(final User user) ;
    public List<User> findAll() ;
    public User findUserById(int id);
}

DAOImpl

Now, let's create the implementation class. This will implement all the UserDao methods. Here, we will be using NamedParameterJdbcTemplate to create and retrieve the record. NamedParameterJdbcTemplate has many methods. We have used 3 methods here to demonstrate how to pass named parameters:

@Repository
public class UserDaoImpl implements UserDao {

private final String INSERT_SQL = "INSERT INTO USERS(name, address, email)  values(:name,:address,:email)";
private final String FETCH_SQL = "select record_id, name, address, email from users";
private final String FETCH_SQL_BY_ID = "select * from users where record_id = :id";

@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public User create(final User user) {
KeyHolder holder = new GeneratedKeyHolder();
SqlParameterSource parameters = new MapSqlParameterSource()
.addValue("name", user.getName())
.addValue("address", user.getAddress())
.addValue("email", user.getEmail());
namedParameterJdbcTemplate.update(INSERT_SQL, parameters, holder);
user.setId(holder.getKey().intValue());
return user;
}

public List<User> findAll() {
return namedParameterJdbcTemplate.query(FETCH_SQL, new UserMapper());
}

public User findUserById(int id) {
Map<String, Integer> parameters = new HashMap<String, Integer>();
parameters.put("id", id);
return (User) namedParameterJdbcTemplate.queryForObject(FETCH_SQL_BY_ID, parameters, new UserMapper());
}

}

class UserMapper implements RowMapper {

@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("record_id"));
user.setName(rs.getString("name"));
user.setAddress(rs.getString("address"));
user.setEmail(rs.getString("email"));
return user;
}

}

1. update() — We have used the update() method to insert the data to USERS table. If we used regular JDBCTemplate, we will be using

StringINSERT_SQL  = "INSERT INTO USERS(name, address, email) values (?,?,?)"; 

But we have used NamedParameterJdbcTemplate so our query string will be like this:   INSERT_SQL = "INSERT INTO USERS(name, address, email)values(:name,:address,:email)"; We see that we are using the named parameters instead of "?".  

2. query() —  We have used the query() method to retrieve all the User records from USERS table. Here our query string will be:   String FETCH_SQL = "select record_id, name, address, email from users";  

This will be the same as any other jdbcTemplate query. No special handling here.

3. queryForObject() — We have used queryForObject() method to retrieve User based on the record_id field. Here we will have query string as below:

 String FETCH_SQL_BY_ID = "select * from users where record_id = :id"; 
If you notice, here we have used the named parameter "id" instead of the "?".

Please also do note that we have used RowMapper to map the resultset with the User object.

Controller

Now, let's quickly expose this functionality through REST so that we can test it easily:

@RestController
public class UserController {
    @Autowired
    private UserDaoImpl userDao;

    @PostMapping("/users")
    public ResponseEntity<User> createUser() {
        User user   =   userDao.create(getUser());
        return ResponseEntity.ok(user);
    }

    @GetMapping("/users")
    public List<User> retrieveAllUsers() {
        return userDao.findAll();

    }
    @GetMapping("/users/{id}")
    public User retrieveUserById(@PathVariable int id ) {
        return userDao.findUserById(id);
    }

    private User getUser() {
User user = new User();
user.setAddress("Marathahalli, Bangalore");
user.setEmail("rajesh.bhojwani@gmail.com");
user.setName("Rajesh Bhojwani");
return user;
}

}

Build and Test

To build this application, we need to run Gradle build command:

 gradlew clean build 

It will generate the jar file under build/libs.

To start the application, we need to run the command:   java -jar build/libs/springbootjdbc-0.0.1-SNAPSHOT.jar 

Now, before testing the application, we need to create the USERS table in the h2 database. So, let's start the h2-console at http://localhost:8100/h2-console. 

Image title

Make sure JDBC URL is updated to jdbc:h2:mem:testdb. And, then click on Connect button.  Now, we can create the schema of the table USERS by running ddl statement.

 CREATE TABLE users (record_id bigint NOT NULL AUTO_INCREMENT, name varchar(100), address varchar(250), email varchar(100), PRIMARY KEY (record_id)); Once the table is created, now we can test our REST APIs to create and retrieve User record.

1. POST call -   http://localhost:8100/users  

2. GET call -    http://localhost:8100/users 

3. GET Call -   http://localhost:8100/users/1 

Conclusion

To summarize, we have seen in this article how to pass named parameters by using NamedParameterJdbcTemplate. 

As usual, the code can be found over Github.

Database

Opinions expressed by DZone contributors are their own.

Related

  • Resolving Parameter Sensitivity With Parameter Sensitive Plan Optimization in SQL Server 2022
  • Comparing Managed Postgres Options on The Azure Marketplace
  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!