Over a million developers have joined DZone.

Spring NamedParameterJdbcTemplate Tutorial

Sign up for the Couchbase Community Newsletter to stay ahead of the curve on the latest NoSQL news, events, and webinars. Brought to you in partnership with Couchbase.

The NamedParameterJdbcTemplate class helps you specify the named parameters insted of classic placeholder('?') argument. Named parameters improves readiablity and are easier to maintain.

package com.vaannila.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import com.vaannila.domain.Forum;

public class ForumDAOImpl implements ForumDAO {

	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public void setDataSource(DataSource dataSource) {
	    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}

	public void insertForum(Forum forum) {
		String query = "INSERT INTO FORUMS (FORUM_ID, FORUM_NAME, FORUM_DESC) VALUES (:forumId,:forumName,:forumDesc)";
		Map namedParameters = new HashMap();
		namedParameters.put("forumId", Integer.valueOf(forum.getForumId()));
		namedParameters.put("forumName", forum.getForumName());
		namedParameters.put("forumDesc", forum.getForumDesc());
		namedParameterJdbcTemplate.update(query, namedParameters);
	}
	
	public Forum selectForum(int forumId) {
		String query = "SELECT * FROM FORUMS WHERE FORUM_ID=:forumId";
		SqlParameterSource namedParameters = new MapSqlParameterSource("forumId", Integer.valueOf(forumId));

		return (Forum) namedParameterJdbcTemplate.queryForObject(query,
				namedParameters, new RowMapper() {
			public Object mapRow(ResultSet resultSet, int rowNum)
					throws SQLException {
				return new Forum(resultSet.getInt("FORUM_ID"), resultSet.getString("FORUM_NAME"), resultSet.getString("FORUM_DESC"));
			}
		});
	}

}

The named parameter values can be specified using a map, where the parameter name serves as the key. You can also map the sql parameters using the MapSqlParameterSource class.

You can download and try the example here.

Source :Download
Source + Lib :Download

 

Are you a developer? Don’t miss the monthly Couchbase Developer Community Newsletter, covering the latest headlines on NoSQL and much more. Brought to you in partnership with Couchbase.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}