文件首頁
MySQL Connector/J 開發者指南
相關文件 下載本手冊
PDF (US Ltr) - 1.2Mb
PDF (A4) - 1.2Mb


15.1 使用 JdbcTemplate

Spring 廣泛使用樣板方法設計模式 (請參閱 樣板方法模式)。我們目前的重點將放在 JdbcTemplate 和相關類別,特別是 NamedParameterJdbcTemplate。樣板類別會處理在需要時取得和釋放資料存取的連線。

下一個範例示範如何在 DAO (資料存取物件) 類別中使用 NamedParameterJdbcTemplate,以擷取給定國家/地區代碼的隨機城市。

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
    */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
}

上述程式碼的重點在於 getRandomCityByCountryCode() 方法。我們傳遞國家/地區代碼,並使用 NamedParameterJdbcTemplate 來查詢城市。國家/地區代碼放置在以 "country" 作為鍵的 Map 中,這是 SQL 查詢中命名的參數。

若要存取此程式碼,您需要透過提供資料來源的參考來使用 Spring 設定它。

<bean id="dao" class="code.Ex2JdbcDao">
    <property name="dataSource" ref="dataSource"/>
</bean>

此時,我們可以只從 Spring 取得 DAO 的參考,並呼叫 getRandomCityByCountryCode()

    // 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 類別 (包括 ConnectionPreparedStatement) 的使用方式。