Home  >  Spring Core

NamedParameterJdbcTemplate Spring Example

By Arvind Rai, October 27, 2013
NamedParameterJdbcTemplate provides the programming facility to take input by name in sql query. In prepared statement we use (?) for input index. NamedParameterJdbcTemplate supports to a name. In our example we are showing how to use NamedParameterJdbcTemplate.

SoldierDao.java
package com.concretepage.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
@Repository
public class SoldierDao {
	private NamedParameterJdbcTemplate namedjdbcTemplate;
    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.namedjdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    }
    public int getSoldierCnt(int sage){
	  String sql = "select count(*) from soldier where age = :age";
	  SqlParameterSource namedParameters = new MapSqlParameterSource("age", sage);
	  return namedjdbcTemplate.queryForInt(sql, namedParameters);    	
    }

}
 


SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.dao.SoldierDao;
public class SpringTest {
	public static void main(String[] args) {
		ApplicationContext  context = new ClassPathXmlApplicationContext("spring.xml");
		SoldierDao soldierDao = (SoldierDao)context.getBean("soldierDao");
		System.out.println(soldierDao.getSoldierCnt(25));
	}
}   
 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us