tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > JDBC > Named Parameter Map Source

Named Parameter Map Source 

Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors. The following example shows querying records using NamedParameterJdbcTemplate and MapSqlParameterSource classes. It extracts the specified named parameters from the given map source for query execution.


File Name  :  
/SpringJDBC001/conf/basic/applicationContext.xml 

File Name  :  
com/bethecoder/tutorials/spring3/tests/NamedParameterMapSourceTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.spring3.tests;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class NamedParameterMapSourceTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    /**
     * Initialize context and get the NamedParameterJdbcTemplate
     */
    ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    DataSource dataSource = (DataSourceappContext.getBean("dataSource");
    NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);

    MapSqlParameterSource namedParameters = new MapSqlParameterSource("start_id"1);
    namedParameters.addValue("end_id"3);
    
    List<Map<String, Object>> rows = template.queryForList(
        "select ID, NAME, AGE from USER where ID >= :start_id and ID < :end_id"
        namedParameters);
    
    System.out.println(rows);
  }

}
   

It gives the following output,
[{ID=1, NAME=Sriram, AGE=2}, {ID=2, NAME=Anu, AGE=28}]



 
  


  
bl  br