连接器和 API 手册 / 第 3 章 MySQL Connector/J 开发人员指南 / 3.13 将 Connector/J 与 Spring 结合使用 /
3.13.1 使用 JdbcTemplate
Spring 广泛使用了模板方法设计模式(请参阅
模板方法模式)。我们当前的重点将放在
JdbcTemplate
和相关类上,特别是NamedParameterJdbcTemplate
. 模板类在需要时处理获取和释放连接以进行数据访问。
下一个示例显示如何
NamedParameterJdbcTemplate
在 DAO(数据访问对象)类内部使用给定国家/地区代码来检索随机城市。
Press CTRL+C to copypublic 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 */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } }
上面代码中的重点是
getRandomCityByCountryCode()
方法。我们传递国家代码并使用
NamedParameterJdbcTemplate
来查询城市。国家代码放置在具有键“country”的 Map 中,这是在 SQL 查询中命名的参数。
要访问此代码,您需要通过提供对数据源的引用来使用 Spring 对其进行配置。
Press CTRL+C to copy<bean id="dao" class="code.Ex2JdbcDao"> <property name="dataSource" ref="dataSource"/> </bean>
此时,我们可以从 Spring 中获取对 DAO 的引用并调用
getRandomCityByCountryCode()
.
Press CTRL+C to copy// Create the application context ApplicationContext ctx = new ClassPathXmlApplicationContext("ex2appContext.xml"); // Obtain a reference to our DAO Ex2JdbcDao dao = (Ex2JdbcDao) ctx.getBean("dao"); String countryCode = "USA"; // Find a few random cities in the US for(int i = 0; i < 4; ++i) System.out.printf("A random city in %s is %s%n", countryCode, dao.getRandomCityByCountryCode(countryCode));
这个例子展示了如何使用 Spring 的 JDBC 类来完全抽象掉传统 JDBC 类的使用,包括Connection
和
PreparedStatement
.