Apache DbUtils工具的一点浅见

   今天小研究了下apache的DbUtils包,看了下apache的官方文档的介绍,这玩意主要可以带来三点好处.
  1. 可以避免内存泄露,大家在使用JDBC的资源时候,有时候可能会忘记关闭Connection,Statement,ResultSet,添加这些资源的close方法是很烦琐,但DbUtils替我们解决了这个问题.
  2. 使用DbUtils代码相较JDBC会简洁不少.而不会为释放资源所烦扰.
  3. 可以自动的将ResultSet中的数据转化为Object.而不用操作大量的set方法.
通过以上几点,可以看出DbUtils给我们操作数据库带来了不少的方便.
       在DbUtils中 最为核心的类和接口是 QueryRunner和ResultSetHandler.其中QueryRunner重载了Connection和DataSource的方法.
   示例代码如下(dataSource):
  
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
}
 
     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);    
}
 
   对于ResultSetHandler,我们可以将ResultSet对象很轻松的转化为一个JavaBean(只查询一个Object),或者一个JavaBean的List集合.这样带来的最大好处就是避免了烦琐的set,set,set,呵呵.示例代码分别如下.
   一个实体Bean的
  
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. 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");    

 
   实体Bean的List模式:
  
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. 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);
 
   ResultSetHandler 是通过实现了RowProcessor接口来实现,默认是
BasicRowProcessor,我们也可以实现自己的类并重写toBean() 方法.
   BeanProcessor类是处理数据库字段和javaBean映射的核心类,我们可以通过给数据库字段加别名或者继承BeanProcessor并重写mapColumnsToProperties方法来实现bean中属性和数据库字段的对应.
 

你可能感兴趣的:(apache,jdbc,职场,DbUtils,休闲)