文件首頁
MySQL Connector/J 開發人員指南
相關文件 下載本手冊
PDF (美式信紙) - 1.2Mb
PDF (A4) - 1.2Mb


MySQL Connector/J 開發人員指南  /  使用 Connector/J 與 Spring

第 15 章 使用 Connector/J 與 Spring

Spring Framework 是一個以 Java 為基礎的應用程式架構,旨在透過提供配置元件的方法來協助應用程式設計。Spring 使用的技術是一種稱為相依性注入的著名設計模式 (請參閱 控制反轉容器和相依性注入模式)。本文將重點介紹使用 Spring 2.0 對 MySQL 資料庫的 Java 導向存取。對於那些想知道的人來說,有一個名為 Spring.NET 的 Spring .NET 連接埠。

Spring 不僅是一個用於配置元件的系統,還包括對面向方面程式設計 (AOP) 的支援。這是 Spring 的主要優點之一,也是 Spring 的資源和交易管理基礎。Spring 還提供用於將資源管理與 JDBC 和 Hibernate 整合的實用工具。

在本節的範例中,將使用 MySQL 世界範例資料庫。第一個任務是透過 Spring 設定 MySQL 資料來源。Spring 中的元件使用 bean 術語。例如,若要設定連線到支援世界範例資料庫的 MySQL 伺服器,您可能會使用

<util:map id="dbProps">
    <entry key="db.driver" value="com.mysql.cj.jdbc.Driver"/>
    <entry key="db.jdbcurl" value="jdbc:mysql://127.0.0.1/world"/>
    <entry key="db.username" value="myuser"/>
    <entry key="db.password" value="mypass"/>
</util:map>

在上述範例中,我們正在為將在組態中使用的屬性指派值。對於資料來源組態

<bean id="dataSource"
       class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${db.driver}"/>
    <property name="url" value="${db.jdbcurl}"/>
    <property name="username" value="${db.username}"/>
    <property name="password" value="${db.password}"/>
</bean>

這些預留位置用於提供這個 bean 的屬性值。這表示我們可以在一處指定組態的所有屬性,而不是在每個 bean 上輸入每個屬性的值。不過,我們還需要另一個 bean 來將所有這些結合在一起。最後一個 bean 負責實際將預留位置替換為屬性值。

<bean
 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties" ref="dbProps"/>
</bean>

現在我們已經設定好 MySQL 資料來源並準備好開始使用,我們編寫一些 Java 程式碼來存取它。下面的範例將使用我們透過 Spring 設定的資料來源來擷取三個隨機城市及其對應的國家/地區。

// Create a new application context. this processes the Spring config
ApplicationContext ctx =
    new ClassPathXmlApplicationContext("ex1appContext.xml");
// Retrieve the data source from the application context
    DataSource ds = (DataSource) ctx.getBean("dataSource");
// Open a database connection using Spring's DataSourceUtils
Connection c = DataSourceUtils.getConnection(ds);
try {
    // retrieve a list of three random cities
    PreparedStatement ps = c.prepareStatement(
        "select City.Name as 'City', Country.Name as 'Country' " +
        "from City inner join Country on City.CountryCode = Country.Code " +
        "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);
}

這與正常的 JDBC 存取 MySQL 非常相似,主要區別在於我們使用的是 DataSourceUtils 而不是 DriverManager 來建立連線。

雖然它看起來似乎是一個小差異,但其含義卻有些深遠。Spring 管理這個資源的方式與 J2EE 應用程式伺服器中的容器管理資料來源類似。當連線開啟時,如果它與交易同步,則可以在程式碼的其他部分中隨後存取它。這使得將應用程式的不同部分視為交易式,而不是傳遞資料庫連線成為可能。