Oracle 5.0 Reference Manual page 2127

Table of Contents

Advertisement

"order by rand() limit 3");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String city = rs.getString("City");
String country = rs.getString("Country");
System.out.printf("The city %s is in %s%n", city, country);
}
} catch (SQLException ex) {
// something has failed and we print a stack trace to analyse the error
ex.printStackTrace();
// ignore failure closing connection
try { c.close(); } catch (SQLException e) { }
} finally {
// properly release our connection
DataSourceUtils.releaseConnection(c, ds);
}
This is very similar to normal JDBC access to MySQL with the main difference being that we are using
DataSourceUtils instead of the DriverManager to create the connection.
While it may seem like a small difference, the implications are somewhat far reaching. Spring manages
this resource in a way similar to a container managed data source in a J2EE application server. When
a connection is opened, it can be subsequently accessed in other parts of the code if it is synchronized
with a transaction. This makes it possible to treat different parts of your application as transactional
instead of passing around a database connection.
20.3.13.1. Using
JdbcTemplate
Spring makes extensive use of the Template method design pattern (see
Pattern). Our immediate focus will be on the
NamedParameterJdbcTemplate. The template classes handle obtaining and releasing a connection
for data access when one is needed.
The next example shows how to use
Object) class to retrieve a random city given a country code.
public class Ex2JdbcDao {
/**
* Data source reference which will be provided by Spring.
*/
private DataSource dataSource;
/**
* Our query to find a random city given a country code. Notice
* the ":country" parameter toward the end. This is called a
* named parameter.
*/
private String queryString = "select Name from City " +
"where CountryCode = :country order by rand() limit 1";
/**
* Retrieve a random city using Spring JDBC access classes.
*/
public String getRandomCityByCountryCode(String cntryCode) {
// A template that permits using queries with named parameters
NamedParameterJdbcTemplate template =
new NamedParameterJdbcTemplate(dataSource);
// A java.util.Map is used to provide values for the parameters
Map params = new HashMap();
params.put("country", cntryCode);
// We query for an Object and specify what class we are expecting
return (String)template.queryForObject(queryString, params, String.class);
}
/**
* A JavaBean setter-style method to allow Spring to inject the data source.
* @param dataSource
*/
Using Connector/J with Spring
JdbcTemplate
NamedParameterJdbcTemplate
2107
Template Method
and related classes, specifically
inside of a DAO (Data Access

Advertisement

Table of Contents
loading

This manual is also suitable for:

Mysql 5.0

Table of Contents