In the previous listing, we use the queryForObject() method of JdbcTemplate to retrieve the value of
the first name. The first argument is the SQL string, and the second argument consists of the parameters
to be passed to the SQL for parameter binding in object array format. The last argument is the type to be
returned, which is String in this case. Besides Object, you can also query for other types like Long and
Integer. Let's take a look at the outcome. Listing 8-25 shows the testing program.
Listing 8-25. Using JdbcTemplate
package com.apress.prospring3.ch8;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.apress.prospring3.ch8.dao.ContactDao;
public class JdbcContactDaoSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context-xml.xml");
ctx.refresh();
ContactDao contactDao = ctx.getBean("contactDao", ContactDao.class);
// Find first name by id
System.out.println("First name for contact id 1 is: " +
contactDao.findFirstNameById(1l));
}
}
As expected, running the program yields the following output:
First name for contact id 1 is: Clarence
Using Named Parameters with NamedParameterJdbcTemplate
In the previous example, we are using the normal placeholder (the ? character) as query parameters. As
you also see, we need to pass the parameters as an Object array. When using a normal placeholder, the
order is very important, and the order that you put the parameters into the array should be the same as
the order of the parameters in the query.
Some developers (like me) prefer to use named parameters to ensure that the parameter is being
bound exactly as wanted. In Spring, a variant of JdbcTemplate, called NamedParameterJdbcTemplate
(under the package org.springframework.jdbc.core.namedparam), provides supports for this. Let's see
how it works.
For example, this time we want to add another method to find the last name by ID, so let's add the
method to the ContactDao interface:
public String findLastNameById(Long id);
The initialization of the NamedParameterJdbcTemplate is the same as JdbcTemplate, so we just need to
declare a variable with type NamedParameterJdbcTemplate and add the following line into the DAO class's
setDataSource() method:
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home