Searching...
Sunday, 1 June 2014

Spring NamedParameterJdbcTemplate Example

04:45

NamedParameterJdbcTemplate has basic set of JDBC operations and allowing the use of named parameters rather than traditional '?' placeholders.
We have to set all params in a map and pass the param map while executing the query.

Spring configuration

 	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/springschema"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	
  	<bean id="namdjdbctemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
     <constructor-arg>
        <ref bean="dataSource"/>
     </constructor-arg>    
     </bean>

Main class

package com.pretech.jdbc;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class NamedParameterJdbcTemplateExample {
	public static void main(String args[]) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				"SpringConfig.xml");
		NamedParameterJdbcTemplate namdjdbctemplate = (NamedParameterJdbcTemplate) appContext
				.getBean("namdjdbctemplate");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("name", "Shiva");
		paramMap.put("standard", "2st standard");
		List<Map<String, Object>> students = namdjdbctemplate
				.queryForList(
						"select * from student where name=:name and standard=:standard",
						paramMap);
		System.out.println(students);
	}
}

0 comments: