Commons DbUtils:JDBC使用組件
Scope of the Package(包的範圍)
Example Usage(使用案例)
英文參見:https://commons.apache.org/proper/commons-dbutils/examples.html基本用法
// 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");
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()方法來處理定製的數據庫數據類型問題。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()方法,以除去這些不合法的字符。