JDBCTemplate 資料讀取機制

來源:互聯網
上載者:User

文章來源: http://publishblog.blogdriver.com/blog/tb.b?diaryID=1182919

 

JDBCTemplate 資料讀取機制

JDBCTemplate 資料讀取

一般的讀取資料的步驟可以用表示:

 

l 確定需要讀取的資料:這一步應該是我們程式員關心的重點。他是我們程式的原始需求。

l 通知數據庫我們的需求:

在直接使用JDBC程式這一步主要是分成如下幾步來完成的。

先註冊一個驅動(驅動由不同的廠商或組織實現。對不同的資料庫伺服器有不同的實現)

典型的註冊方法:

Class.forName("my.sql.Driver");

然後通過DriverManager來建立一個資料庫連接。

接著我們的程式就通過這個資料庫連接和資料庫伺服器互動。我們發送查詢請求只是各種互動的一種。而我們的請求的內容是根據我們的需求而確定的(其實就是Sql語句需要查詢的內容了)。

這部分的工作可分為三部分:

  和資料庫伺服器建立串連。

  根據需求組織請求內容(確定查詢語句)。

  通過串連向資料庫伺服器發送請求。

在以上的三步中其中第一步和第三步是約定好的。在JDBC程式中的典型實現方式為

//第一步

Class.forName("my.sql.Driver");

conn = DriverManager.getConnection(dbUrl);

//第二步

sql = GenerateSql();

//第三步

stmt = this.conn.createStatement();

rs = stmt.executeQuery(sql);

在這裡我們應該把更多的注意點關注到第二步。

l 等待的過程我們就無能為力。這個牽涉到的東西很多包括網路,驅動的實現以及資料庫伺服器的效能。

l 組織資料。這應該是我們實現取資料目的的前驟。把關係型資料群組織成我們方便使用的類型。如實體物件等。(其實這部分的工作可以用其他的O/R mapping架構來實現,但是這個不是今天想討論的問題)這一部分複雜多樣。只能由我們自己來實現。

l 通知數據程式庫伺服器請求結束。這一部分的工作應包括清理一些資料庫資源,如資料庫連接等。雖然很繁瑣但是很重要,如果不做的話很有可能造成資源泄漏,在嚴重的情況下可能引發OutofMenory錯誤,導致系統癱瘓。很多時候我們會忘掉這個步驟。這個部分最好由工具完成。

l 使用是我們目標的一個實現。不多提了。

從上面的分析可以看出有兩部分有很大的靈活性。

1. 向資料庫伺服器發送請求的請求組織部分。說白了也就sql語句的寫法。

2. 組織資料部分。資料庫讀出來後把資料群組織成我們所需要的格式。

做為一個Template,JDBCTemplate為我們做好了通用的動作,及除了上述兩點外的說有動作。並為上述兩點提供了靈活方便的介面。

核心的介面有兩個: PreparedStatementCreator和RowCallBackHandler

l PreparedStatementCreator

該介面只有一個方法需要實現。PreparedStatement createPreparedStatement(Connection con) throws SQLException;定製我們自己的查詢條件。

下面的英文節選自Expert One ? on ? One J2EE Design and Development中的描述。

關於這本書和Spring架構的關係可以這麼理解書是架構的最好說明。或者說架構是書的附帶源碼。

The PreparedStatementCreator interface must be implemented by application-specific classes to create a java.sql.PreparedStatement, given a java.sql.Connection. This means specifying the SQL and setting bind parameters for an application-specific query or update, which will be run by the JdbcTemplate class. Note that an implementation of this interface doesn't need to worry about obtaining a connection or catching any SQLExceptions that may result from its work. The PreparedStatement it creates will be executed by the JdbcTemplate class. The interface is as follows:

   public interface PreparedStatementCreator { 

     PreparedStatement createPreparedStatement (Connection conn)

       throws SQLException;

   }

The following shows a typical implementation, which uses standard JDBC methods to construct a PreparedStatement with the desired SQL and set bind variable values. Like many implementations of such simple interfaces, this is an anonymous inner class:

   PreparedStatementCreator psc = new PreparedStatementCreator() {

 

     public PreparedStatement createPreparedStatement (Connection conn)

         throws SQLException {

       PreparedStatement ps = conn. prepareStatement (

         "SELECT seat_id AS id FROM available_seats WHERE " +

         "performance_id = ? AND price_band_id = ?");

       ps.setInt(1, performanceId);

       ps.setInt(2, seatType);

       return ps;

     }

   };

The PreparedStatementCreatorFactory class is a generic helper that can be used repeatedly to create PreparedStatementCreator objects with different parameter values, based on the same SQL statement and bind variable declarations. This class is largely used by the higher-level, object-abstraction framework described below; application code will normally define PreparedStatementCreator classes as shown above.

 

 

 

 

l         RowCallbackHandler

The RowCallbackHandler interface must be implemented by application-specific classes to extract column values from each row of the ResultSet returned by a query. The JdbcTemplate class handles iteration over the ResultSet. The implementation of this interface may also leave SQLExceptions uncaught: the JdbcTemplate will handle them. The interface is as follows:

   public interface RowCallbackHandler {

     void processRow(ResultSet rs) throws SQLException;

   }

Implementations should know the number of columns and data types to expect in the ResultSet. The following shows a typical implementation, which extracts an int value from each row and adds it to a list defined in the enclosing method:

 

   RowCallbackHandler rch = new RowCallbackHandler() {

     public void processRow(ResultSet rs) throws SQLException {

       int seatId = rs.getInt(1) ;

       list.add(new Integer (seatId) );

     }

   };

The RowCountCallbackHandler class is a convenient framework implementation of this interface that stores metadata about column names and types and counts the rows in the ResultSet. Although it's a concrete class, its main use is as a superclass of application-specific classes.

The ResultReader interface extends RowCallbackHandler to save the retrieved results in a java.util.List:

   public interface ResultReader extends RowCallbackHandler {

     List getResults() ;

   }

The conversion of each row of the ResultSet to an object is likely to vary widely between implementations, so there is no standard implementation of this interface.

到這兒JDBCTemplate其實已經建立起了個很完畢的資料庫讀取機制。下面我們將JDBCTemplate是如何?資料庫的讀取。我們就來看看如何使用JDBCTemplate來實現資料庫的查詢。

RowCallBackHandler的使用

public class BookDaoJdbc extends com.jet.springtest.dao.AbstractDaoJdbc   {

public List readAllBook() {

      

              String sql = "SELECT id,name,publisher,isbn FROM spring.book ";

              getJdbcTemplate().query(sql, new RowCallbackHandler(){

                     public void processRow(ResultSet rs) throws SQLException {

                            Book currentBook = new Book();

                            currentBook.setFBookName(rs.getString("name"));

                            currentBook.setFPublisher(rs.getString("publisher"));

                            currentBook.setFIsbn(rs.getString("isbn"));

                            currentBook.setFId(new Integer(rs.getInt("id")));

                            fBooks.add(currentBook);

                     }

              });

}

              return fBooks;

 

 

 

 

}

注意看一下new RowCallbackHandler()部分。這部分其實是我們實現了一個RowCallbackHandler介面的匿名類。我們必須實現一個processRow(ResultSet rs)的方法供JDBCTemplate回調。跟蹤一下可以發現有如下的調用路徑。

 

 

 

說明:這裡有兩個很有用的技巧。

1、  使用介面實現回調的功能。

2、  內部類的實用。

問題你一定想問一下我們如何得到資料庫連接,開啟並關閉呢?這所有的動作都是由Template在execute中幫我們完成的。通過下面的代碼得到證實。

 

我們可以清晰地看到Template幫我們做的一切,不用再擔心Connection沒有關閉而導致系統垮掉的可能。

PreparedStatementCreator的使用

在上面的例子中我們已經看到RowCallBackHandler的作用是在資料群組織這一塊。PreparedStatementCreator的作用就是為了“向資料庫伺服器發送請求的請求組織部分”而服務的了。

 

這裡只是簡單的示範和解釋了一下JDBCTemplate中的資料讀取的機制。他還提供很多其它的查詢和更新的介面。簡單的說JDBCTemplate可以讓你只關注你需要關注的地方。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.