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()方法,以除去这些不合法的字符。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值