Spring Data -NamedParameterJdbcTemplate
NamedParameterJdbcTemplate class
Spring provides another way to insert data by named parameter. In such way, we use names instead of? (question mark), like below
insert into student values (:sno,:name,:address)
NamedParameterJdbcTemplate Example
public class StudentDao {
private NamedParameterJdbcTemplate jdbcTemplate;
public StudentDao(NamedParameterJdbcTemplate jdbcTemplate) {
super();
this.jdbcTemplate = jdbcTemplate;
}
public void saveStudent(Student e) {
String query = "insert into Student values (:sno,:name,:address)";
Map<String, Object> map = new HashMap<String, Object>();
map.put("sno", e.getSno());
map.put("name", e.getName());
map.put("address", e.getAddress());
jdbcTemplate.execute(query, map, new PreparedStatementCallback() {
@Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}
}
<!-- File : SpringConfig.xml -->
<beans>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/smlcodes" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jtemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="dao" class="StudentDao">
<constructor-arg>
<ref bean="jtemplate" />
</constructor-arg>
</bean>
</beans>
//File: JdbcTestApplication.java
public class JdbcTestApplication {
public static void main(String[] args) {
Resource res = new ClassPathResource("SpringConfig.xml");
BeanFactory factory = new XmlBeanFactory(res);
StudentDao dao = (StudentDao) factory.getBean("dao");
Student s = new Student(103, "KAVETI", "HYDERABAD");
dao.saveStudent(s);
}
}
PREVIOUS-JdbcTemplate