Commons DbUtils 使用总结

jopen 10年前

DBUtils是个小巧的JDBC轻量级封装的工具包,其最核心的特性是结果集的封装,可以直接将查询出来的结果集封装成JavaBean,这就为我们做了最枯燥乏味、最容易出错的一大部分工作。
  在使用DBUtils之前,应该注意一些问题:
  1、DBUtils是JDBC的简单封装,可以和JDBC混合使用。
  2、DBUtils对结果集自动封装为JavaBean是有着苛刻要求的:必须满足JavaBean的规范,其次Bean的getter与setter方法的名字与结果集的列名一一对应,而不要求JavaBean的私有成员与表结果集列名一一对应。
  比如:
  person表中有个字段叫:address,那么对应的JavaBean的Person类中必须有getAddress和setAddress两个方法,而Person类中可以将address属性命名为add,这是没问题的。
  3、DBUtils可以将结果集封装为各种类型,主要有:Bean/List<Bean>,Map/List<Map>/Map<Map>,数组/List<数组>,列/List<列>,这些类型。
  对于Map<Map>的类型使用KeyedHandler作为结果集处理器,内层的Map是“列名-值"对,外层的Map是“主键-内层Map的引用”,但此处的主键不一定就是数据库的主键,可以随意指定,比如:
  ResultSetHandler h = new KeyedHandler("id");
  Map found = (Map) queryRunner.query("select id, name, age from person", h);
  Map jane = (Map) found.get(new Long(1)); // jane's id is 1
  String janesName = (String) jane.get("name");
  Integer janesAge = (Integer) jane.get("age");
  4、DBUtils执行插入操作的时候,无法返回自增主键,这是一个很严重的问题,当然不能怪DBUtils,可以通过变通的方法来实现,比如在MySQL中,执行完了一个插入SQL后,接着执行SELECT LAST_INSERT_ID()语句,就可以获取到自增主键。
  5、DBUtils的性能和JDBC性能是一样,测试过程中没发现性能损失,拥有了很高性能的同时,而不失JDBC的灵活性。
  6、对于JavaBean的成员类型定义,有一条原则那就是:尽可能使用包装类型,而不要使用基本类型。很多人不理解为什么,包括我见到一些傻B(,我提出让改为包装类型,他还信誓旦旦的说他的代码多牛多叼),都干好多年了,这个简单的道理还不知道:

        //错误
        int a1 = (Integer) null;
        boolean x1 = (Boolean)null;
        //正确
        Integer a2 = (Integer) null;
        Boolean x2 = (Boolean)null;
实际上就是为了保证在查询结果为null的时候,也不会因为给基本类型赋null值而发生错误。
下面给出一个简单例子,作为以后写代码时候有点参考:
环境:
MySQL5.4
JDK1.5
建表SQL:
CREATE TABLE person (
     id bigint(20) NOT NULL AUTO_INCREMENT,
     name varchar(24) DEFAULT NULL,
     age int(11) DEFAULT NULL,
     address varchar(120) DEFAULT NULL,
     PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=gbk
Java代码:
public class Person {
        private Long id;
        private String sdf;
        private String address2;
        private Integer age;
        public Person() {
        }
        public Person(String sdf) {
                this.sdf = sdf;
        }
        public Person(String sdf, Integer age, String address) {
                this.sdf = sdf;
                this.age = age;
                this.address2 = address;
        }
        public Long getId() {
                return id;
        }
        public void setId(Long id) {
                this.id = id;
        }
        public String getSdf() {
                return sdf;
        }
        public void setSdf(String sdf) {
                this.sdf = sdf;
        }
        public Integer getAge() {
                return age;
        }
        public void setAge(Integer age) {
                this.age = age;
        }
        public String getAddress() {
                return address2;
        }
        public void setAddress(String address2) {
                this.address2 = address2;
        }
}
测试
package com.lavasoft.dbstu;
import com.lavasoft.common.DBToolkit;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/
Created by IntelliJ IDEA.

@author leizhimin 2010-1-25 21:00:29
/
public class PersonDAOImpl implements PersonDAO {
        private static PersonDAOImpl instance = new PersonDAOImpl();
        public static PersonDAOImpl getInstance() {
                return instance;
        }
        public static void main(String[] args) {
                //错误
                int a1 = (Integer) null;
                boolean x1 = (Boolean) null;
                //正确
                Integer a2 = (Integer) null;
                Boolean x2 = (Boolean) null;
                getInstance().save(null);
//                getInstance().save(null);
//                getInstance().save(null);
//                getInstance().save(null);
//                getInstance().save(null);
                getInstance().update(null);
                getInstance().load(null);
                getInstance().load4Map(null);
        }
        @Override
        public Long save(String sql) {
                Long id = null;
                String ins_sql = "INSERT INTO person (NAME, age, address) VALUES ('aaa', 21, 'address001')";
                Connection conn = DBToolkit.getConnection();
                QueryRunner qr = new QueryRunner();
                try {
                        qr.update(conn, ins_sql);
                        //获取新增记录的自增主键
                        id = (Long) qr.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler(1));
                } catch (SQLException e) {
                        e.printStackTrace();
                } finally {
                        DBToolkit.closeConnection(conn);
                }
                return id;
        }
        @Override
        public int delete(Long id) {
                int x = 0;
                Connection conn = DBToolkit.getConnection();
                QueryRunner qr = new QueryRunner();
                try {
                        x = qr.update(conn, "DELETE FROM person WHERE id = ?", id);
                } catch (SQLException e) {
                        e.printStackTrace();
                } finally {
                        DBToolkit.closeConnection(conn);
                }
                return x;
        }
        @Override
        public int update(Person person) {
                int x = 0;
                Connection conn = DBToolkit.getConnection();
                QueryRunner qr = new QueryRunner();
                try {
                        x = qr.update(conn, "UPDATE person SET NAME = ?, age = ?, address = ? WHERE id = ?", "xxx", 23, "ttt", 5);
                } catch (SQLException e) {
                        e.printStackTrace();
                } finally {
                        DBToolkit.closeConnection(conn);
                }
                return x;
        }
        @Override
        public Person load(Long id) {
                Connection conn = DBToolkit.getConnection();
                QueryRunner qr = new QueryRunner();
                try {
                        Person person = (Person) qr.query(conn, "SELECT FROM person where id = ?", new BeanHandler(Person.class), 3L);
                        System.out.println(person.getId() + "\t" + person.getSdf() + "\t" + person.getAge() + "\t" + person.getAddress());
                } catch (SQLException e) {
                        e.printStackTrace();
                }
                return null;
        }
        @Override
        public List<Person> findPerson(String sql) {
                Connection conn = DBToolkit.getConnection();
                QueryRunner qr = new QueryRunner();
                try {
                        List<Person> pset = (List) qr.query(conn, "SELECT
FROM person", new BeanListHandler(Person.class));
                        for (Person person : pset) {
                                System.out.println(person.getId() + "\t" + person.getSdf() + "\t" + person.getAge() + "\t" + person.getAddress());
                        }
                } catch (SQLException e) {
                        e.printStackTrace();
                }
                return null;
        }
        public Person load4Map(Long id) {
                Connection conn = DBToolkit.getConnection();
                QueryRunner qr = new QueryRunner();
                try {
                        //先将两个字段置为null
                        qr.update(conn, "update person set age = null,address =null where id =1");
                        Map<String, Object> map = qr.query(conn, "SELECT FROM person where id = ?", new MapHandler(), 1L);
                        Person person = new Person();
                        person.setId((Long) map.get("id"));
                        person.setSdf((String) map.get("name"));
                        person.setAge((Integer) map.get("age"));
                        person.setAddress((String) map.get("address"));
                        System.out.println(person.getId() + "\t" + person.getSdf() + "\t" + person.getAge() + "\t" + person.getAddress());
                } catch (SQLException e) {
                        e.printStackTrace();
                }
                return null;
        }
}
注意:
从上面的过程看,每个SQL的执行都需要用到QueryRunner,这其实是一个普通的类,非线程安全。在创建这个QueryRunner对象的时候,每次都要new。
QueryRunner对象的创建方式很多,可以通过DateSource,也可以通过Connection来创建。从QueryRunner对象上,可以直接获取到DataSource或者Connection对象。
Dbutil 的使用示例
代码
package cn.lining.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
public class test {
 @SuppressWarnings("unchecked")
 public static void main(String[] args) throws ClassNotFoundException {
  UserField userField = new UserField();
  Connection conn = null;
  String jdbcURL = "jdbc:mysql://localhost:3306/macaw4";
  String jdbcDriver = "com.mysql.jdbc.Driver";
  try {
   DbUtils.loadDriver(jdbcDriver);
   conn = DriverManager.getConnection(jdbcURL, "root", "root");
   conn.setAutoCommit(false);//关闭自动提交
   QueryRunner qRunner = new QueryRunner();
   // 以下部分代码采用MapHandler存储方式查询
   System.out.println("
Using MapHandler");
   Map map = (Map) qRunner.query(conn,
     "select
from mc_user_field where id = ?",
     new MapHandler(), new Object[] { "5" });
   System.out.println("id ------------- name ");
   System.out.println(map.get("id") + "  ------------- "
     + map.get("name"));
   // 以下部分代码采用MapListHandler存储方式查询
   System.out.println("*
Using MapListHandler");
   List lMap = (List) qRunner.query(conn,
     "select
from mc_user_field", new MapListHandler());
   System.out.println("id ------------- name ");
   for (int i = 0; i < lMap.size(); i++) {
    Map vals = (Map) lMap.get(i);
    System.out.println(vals.get("id") + "  ------------- "
      + vals.get("name"));
   }
   // 以下部分代码采用BeanHandler存储方式查询
   System.out.println("*
Using BeanHandler");
   userField = (UserField) qRunner.query(conn,
     "select
from mc_user_field where id = ?",
     new BeanHandler(Class.forName("cn.lining.test.UserField")),
     new Object[] { "5" });
   System.out.println("id ------------- name ");
   System.out.println(userField.getId() + "  ------------- "
     + userField.getName());
   // 以下部分代码采用BeanListHandler存储方式查询
   System.out.println("*
Using BeanListHandler");
   List lBean = (List) qRunner.query(conn,
     "select
from mc_user_field", new BeanListHandler(Class
       .forName("cn.lining.test.UserField")));
   System.out.println("id ------------- name ");
   for (int i = 0; i < lBean.size(); i++) {
    userField = (UserField) lBean.get(i);
    System.out.println(userField.getId() + "  ------------- "
      + userField.getName());
   }
   // 以下部分代码采用ArrayHandler存储方式查询
   System.out.println("*
Using ArrayHandler");
   Object[] array = (Object[]) qRunner.query(conn,
     "select
from mc_user_field where id = ?",
     new ArrayHandler(), new Object[] { "5" });
   System.out.println("id ------------- name ");
   System.out.println(array[0].toString() + "  ------------- "
     + array[1].toString());
   // 以下部分代码采用ArrayListHandler存储方式查询
   System.out.println("*
Using ArrayListHandler");
   List lArray = (List) qRunner.query(conn,
     "select
from mc_user_field", new ArrayListHandler());
   System.out.println("id ------------- name ");
   for (int i = 0; i < lArray.size(); i++) {
    Object[] var = (Object[]) lArray.get(i);
    System.out.println(var[0].toString() + "  ------------- "
      + var[1].toString());
   }
   // 以下部分代码采用ColumnListHandler存储方式查询指定列
   System.out.println("*
Using ColumnListHandler");
   List lName = (List) qRunner.query(conn,
     "select
from mc_user_field where id = ?",
     new ColumnListHandler("name"), new Object[] { "5" });
   System.out.println("name ");
   for (int i = 0; i < lName.size(); i++) {
    String name = (String) lName.get(i);
    System.out.println(name);
   }
   // 以下部分代码采用ScalarHandler存储方式查询
   System.out.println("*
Using ScalarHandler");
   String name = (String) qRunner.query(conn,
     "select
from mc_user_field where id = ?",
     new ScalarHandler("name"), new Object[] { "5" });
   System.out.println("name ");
   System.out.println(name);
   // 以下部分代码采用KeyedHandler存储方式查询
   System.out.println("*
Using KeyedHandler");
   Map<String, Map> map2 = (Map<String, Map>) qRunner.query(conn,
     "select
from mc_user_field", new KeyedHandler("name"));
   System.out.println("name: field_name2");
   Map vals = (Map) map2.get("field_name2");
   System.out.println(vals.get("id") + "  " + vals.get("name") + "  "
     + vals.get("type"));
   // 以下部分代码插入一条数据
   System.out.println("*
Insert begin");
   userField = new UserField();
   qRunner.update(conn, "insert into mc_user_field ("
     + "id,name,type,sort_order,required,visible)"
     + "values (?,?,?,?,?,?)", new Object[] { userField.getId(),
     userField.getName(), userField.getType(),
     userField.getSort_order(), userField.getRequired(),
     userField.getVisible() });
   System.out.println("
update end");
   // 以下部分代码更新一条数据
   System.out.println("
update begin");
   userField = new UserField();
   qRunner.update(conn, "update mc_user_field set "
     + "name = ?,type = ?,sort_order = ?,"
     + "required = ?,visible = ?" + "where id = ?",
     new Object[] { userField.getName(), userField.getType(),
       userField.getSort_order(), userField.getRequired(),
       userField.getVisible(), userField.getId() });
   System.out.println("
update end");
   // 以下部分代码删除一条数据
   System.out.println("
delete begin");
   userField = new UserField();
   qRunner.update(conn, "delete from mc_user_field where id2 = ?",
     new Object[] { userField.getId() });
   System.out.println("
delete end");
  } catch (SQLException ex) {
   ex.printStackTrace();
   try {
    System.out.println("
rollback begin");
    DbUtils.rollback(conn);
    System.out.println("
rollback end***");
   } catch (SQLException e) {
    e.printStackTrace();
   }
  } finally {
   DbUtils.closeQuietly(conn);
  }
 }
}
·  ArrayHandler:把结果集中的第一行数据转成对象数组。
·  ArrayListHandler:把结果集中的每一行数据都转成一个对象数组,再存放到List中。
·  BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
·  BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
·  ColumnListHandler:将结果集中某一列的数据存放到List中。
·   KeyedHandler:将结果集中的每一行数据都封装到一个Map里,然后再根据指定的key把每个Map再存放到一个Map里。
·   MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
·   MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List。
·   ScalarHandler:将结果集中某一条记录的其中某一列的数据存成Object。