Keep Traveling

Spring NamedParameterJdbcTemplate Example

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);
	}
}

No comments:

Post a Comment

Featured Post

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts