org.apache.commons.dbutils 的API學習(1)

Commons DbUtils:JDBC使用組件

英文參見:https://commons.apache.org/proper/commons-dbutils/index.html

Commons DbUtils 庫是一組小的類,旨在位了簡化JDBC工作。JDBC資源清理代碼是普通的、容易出錯的工作,因此這些類從您的代碼中抽象出所有清理任務,從而使您真正想要做的事情是:查詢和更新數據。
使用DbUtils的一些優點是:

1、沒有資源泄漏的可能性。正確的JDBC編碼並不困難,但它是耗時且乏味的。這常常導致連接的泄漏,這可能難以追蹤。
2、更清潔、更清晰的持久性代碼。在數據庫中保存數據所需的代碼量大大減少了。剩下的代碼清楚地表達了您的意圖,而不需要對資源清理混亂。
3、自動從resultset中填充JavaBean屬性。您不需要通過調用setter方法手動將列值複製到bean實例中。ResultSet的每一行都可以由一個完全填充的bean實例來表示。

Scope of the Package(包的範圍)

DbUtils設計特點:
1、小巧-你應該能在短時間內理解整個包裝。
2、透明-DbUtils在幕後沒有任何魔法。您給它一個查詢,它執行它併爲您清理。
3、快速-您不需要創建一百萬個臨時對象來處理DbUtils。

DbUtils不是以下範疇:
1、一個對象/關係橋——已經有很多好的對象/關係工具。DbUtils是面向希望使用JDBC的開發人員,而不是所有的普通部分。
2、一個數據訪問對象(DAO)框架——DbUtils可以用來構建一個DAO框架。
3、面向對象的一般數據庫對象的抽象,如表、列或PrimaryKey。
4、任何類型的重量級框架——(DbUtils)這裏的目標都是簡單易用的JDBC幫助庫。

Example Usage(使用案例)

英文參見:https://commons.apache.org/proper/commons-dbutils/examples.html

基本用法

DbUtils 是一個小的類庫,所以我們不需要花費太多時間就可以在各個類中輕鬆使用它。在DbUtils的核心類/接口是QueryRunner 和 ResultSetHandler。你不需要了解任何其他DbUtils類,用的時候就知道了。下面的案例演示這些類如何在一起使用:
// Create a ResultSetHandler implementation to convert the
// first row into an Object[].
ResultSetHandler<Object[]> h = new ResultSetHandler<Object[]>() {
    public Object[] handle(ResultSet rs) throws SQLException {
        if (!rs.next()) {
            return null;
        }
    
        ResultSetMetaData meta = rs.getMetaData();
        int cols = meta.getColumnCount();
        Object[] result = new Object[cols];

        for (int i = 0; i < cols; i++) {
            result[i] = rs.getObject(i + 1);
        }

        return result;
    }
};

// Create a QueryRunner that will use connections from
// the given DataSource
QueryRunner run = new QueryRunner(dataSource);

// Execute the query and get the results back from the handler
Object[] result = run.query(
    "SELECT * FROM Person WHERE name=?", h, "John Doe");

你可以在查詢前使用 java.sql.Connection對象替代數據源對象。請注意,你要負責關閉本例中的連接。
ResultSetHandler<Object[]> h = ... // Define a handler the same as above example

// No DataSource so we must handle Connections manually
QueryRunner run = new QueryRunner();

Connection conn = ... // open a connection
try{
    Object[] result = run.query(
        conn, "SELECT * FROM Person WHERE name=?", h, "John Doe");
    // do something with the result
} finally {
    // Use this helper method so we don't have to check for null
    DbUtils.close(conn);  
}

您不僅可以從數據庫獲取數據,還可以插入或更新數據。下面的例子將首先把person數據插入到數據庫中,然後再修改person的高度。
QueryRunner run = new QueryRunner( dataSource );
try
{
    // Execute the SQL update statement and return the number of
    // inserts that were made
    int inserts = run.update( "INSERT INTO Person (name,height) VALUES (?,?)",
                              "John Doe", 1.82 );
    // The line before uses varargs and autoboxing to simplify the code

    // Now it's time to rise to the occation...
    int updates = run.update( "UPDATE Person SET height=? WHERE name=?",
                              2.05, "John Doe" );
    // So does the line above
}
catch(SQLException sqle) {
    // Handle it
}

對於長時間運行的調用,您可以使用AsyncQueryRunner來異步地執行調用。AsyncQueryRunner類具有與QueryRunner調用相同的方法;但是,這些方法返回一個可調用的對象。
ExecutorCompletionService<Integer> executor =
    new ExecutorCompletionService<Integer>( Executors.newCachedThreadPool() );
AsyncQueryRunner asyncRun = new AsyncQueryRunner( dataSource );

try
{
    // Create a Callable for the update call
    Callable<Integer> callable = asyncRun.update( "UPDATE Person SET height=? WHERE name=?",
                                                  2.05, "John Doe" );
    // Submit the Callable to the executor
    executor.submit( callable );
} catch(SQLException sqle) {
    // Handle it
}

// Sometime later (or in another thread)
try
{
   // Get the result of the update
   Integer updates = executor.take().get();
} catch(InterruptedException ie) {
    // Handle it
}

ResultSetHandler Implementations

在上面的例子中,我們實現了將ResultSet(結果集)的第一行轉換爲對象的ResultSetHandler的接口。這是一個相當通用的實現,可以跨多個項目重用。在識別DbUtils org.apache.commons.dbutils.handlers包中提供了一組ResultSetHandler實現執行常見的轉換成數組,地圖,和javabean。每個實現都有一個版本,它只轉換第一行,而另一個實現轉換結果集中的所有行。

我們將從一個示例開始,使用BeanHandler從ResultSet獲取一行並將其轉換爲JavaBean。

QueryRunner run = new QueryRunner(dataSource);

// Use the BeanHandler implementation to convert the first
// ResultSet row into a Person JavaBean.
ResultSetHandler<Person> h = new BeanHandler<Person>(Person.class);

// Execute the SQL statement with one replacement parameter and
// return the results in a new Person object generated by the BeanHandler.
Person p = run.query(
    "SELECT * FROM Person WHERE name=?", h, "John Doe"); 

這一次,我們將使用BeanListHandler從ResultSet中獲取所有行,並將它們轉換爲javabean列表。
QueryRunner run = new QueryRunner(dataSource);

// Use the BeanListHandler implementation to convert all
// ResultSet rows into a List of Person JavaBeans.
ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class);

// Execute the SQL statement and return the results in a List of
// Person objects generated by the BeanListHandler.
List<Person> persons = run.query("SELECT * FROM Person", h);

Custom RowProcessor

每個提供的ResultSetHandler實現都接受一個行處理器來實際地將行轉換成對象。默認情況下,處理程序使用BasicRowProcessor實現,但是您可以實現一個自定義版本來插入。可能最常見的定製是實現toBean()方法來處理定製的數據庫數據類型問題。

Custom BeanProcessor

basicrow處理器使用一個BeanProcessor將ResultSet列轉換爲JavaBean屬性。您可以對處理步驟進行子類化和覆蓋,以處理特定於應用程序的數據類型映射。所提供的實現將數據類型轉換委託給JDBC驅動程序。

BeanProcessor在BeanProcessor.toBean()javadoc中將列映射到bean屬性。列名必須在敏感的情況下與bean的屬性名稱相匹配。例如,firstname列將通過調用它的setFirstName()方法存儲在bean中。但是,許多數據庫列名稱包括不能使用的字符,或者在Java方法名中不常用的字符。您可以執行以下操作之一來將這些列映射到bean屬性:

1、在SQL中別名列名,以便與Java名稱匹配:[select social_sec# as socialSecurityNumber from person]

2、子類BeanProcessor並覆蓋mapcolumnstopropertie()方法,以除去這些不合法的字符。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章