commons-dbutils源码学习

我们先来看看经典的JDBC操作数据库

  • 加载数据库驱动
  • 创建数据库连接
  • 创建一个Statement
  • 执行SQL语句
  • 处理返回结果
  • 关闭连接

为了提高性能,利用连接池,很好的解决了获取数据库连接,复用数据库连接,但是还有执行SQL,处理返回结果还是没有抽离出来,为了让代码更好的解耦,我们来看看DBUtils是怎么做的!DBUtils主要做了两件事,一件是填充执行SQL语句参数,另外一件是处理返回结果,封装从对象实体。

只看主要代码,从QueryRunner.query()入口方法开始

    private <T> T query(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params)
            throws SQLException {
        //省略不重要的代码
        PreparedStatement stmt = null;
        ResultSet rs = null;
        T result = null;

        try {
            stmt = this.prepareStatement(conn, sql);
            //封装SQL参数
            this.fillStatement(stmt, params);
            //查询数据库
            rs = this.wrap(stmt.executeQuery());
            //封装数据库返回结果为相应的对象实体
            result = rsh.handle(rs);
        } catch (SQLException e) {
            this.rethrow(e, sql, params);
        } finally {
            try {
                close(rs);
            } finally {
                close(stmt);
                if (closeConn) {
                    close(conn);
                }
            }
        }
        return result;
    }

fillStatement方法操作逻辑如下:

  • 通过Statement.getParameterMetaData() 获取SQL参数实体对象ParameterMetaData
  • 赋值变量params数组,遍历顺序需要跟SQL参数顺序一致
//比如如下两个参数,需要按顺序填充
String sql = "select * from user where groupId=? and sex=?";
Object[] params = new Object[2];
params[0] = groupId;
params[1] = sex;

fillStatement方法代码如下:

public void fillStatement(PreparedStatement stmt, Object... params)
            throws SQLException {

        // check the parameter count, if we can
        ParameterMetaData pmd = null;
        if (!pmdKnownBroken) {
            try {
                pmd = stmt.getParameterMetaData();
                if (pmd == null) { // can be returned by implementations that don't support the method
                    pmdKnownBroken = true;
                } else {
                    int stmtCount = pmd.getParameterCount();
                    int paramsCount = params == null ? 0 : params.length;
        
                    if (stmtCount != paramsCount) {
                        throw new SQLException("Wrong number of parameters: expected "
                                + stmtCount + ", was given " + paramsCount);
                    }
                }
            } catch (SQLFeatureNotSupportedException ex) {
                pmdKnownBroken = true;                
            }
            // TODO see DBUTILS-117: would it make sense to catch any other SQLEx types here?
        }

        // nothing to do here
        if (params == null) {
            return;
        }

        CallableStatement call = null;
        if (stmt instanceof CallableStatement) {
            call = (CallableStatement) stmt;
        }

        for (int i = 0; i < params.length; i++) {
            if (params[i] != null) {
                if (call != null && params[i] instanceof OutParameter) {
                    ((OutParameter)params[i]).register(call, i + 1);
                } else {
                    stmt.setObject(i + 1, params[i]);
                }
            } else {
                // VARCHAR works with many drivers regardless
                // of the actual column type. Oddly, NULL and
                // OTHER don't work with Oracle's drivers.
                int sqlType = Types.VARCHAR;
                if (!pmdKnownBroken) {
                    // TODO see DBUTILS-117: does it make sense to catch SQLEx here?
                    try {
                        /*
                         * It's not possible for pmdKnownBroken to change from
                         * true to false, (once true, always true) so pmd cannot
                         * be null here.
                         */
                        sqlType = pmd.getParameterType(i + 1);
                    } catch (SQLException e) {
                        pmdKnownBroken = true;
                    }
                }
                stmt.setNull(i + 1, sqlType);
            }
        }
    }

handle方法操作逻辑如下:

拿BeanHandler来分析

public T handle(ResultSet rs) throws SQLException {
        return rs.next() ? this.convert.toBean(rs, this.type) : null;
 }
public <T> T toBean(ResultSet rs, Class<? extends T> type) throws SQLException {
        return this.convert.toBean(rs, type);
 }
public <T> T toBean(ResultSet rs, Class<? extends T> type) throws SQLException {
        //创建返回实体对象
        T bean = this.newInstance(type);
        //填充返回实体对象,属性必须应有set方法
        return this.populateBean(rs, bean);
}

主要看populateBean方法

public <T> T populateBean(ResultSet rs, T bean) throws SQLException {
        //获取对象的属性数组
        PropertyDescriptor[] props = this.propertyDescriptors(bean.getClass());
        ResultSetMetaData rsmd = rs.getMetaData();
        //保存数据库返回结果字段对应实体对象属性关系
        int[] columnToProperty = this.mapColumnsToProperties(rsmd, props);
        //填充实体属性
        return populateBean(rs, bean, props, columnToProperty);
}
    private PropertyDescriptor[] propertyDescriptors(Class<?> c)
        throws SQLException {
        // Introspector caches BeanInfo classes for better performance
        BeanInfo beanInfo = null;
        try {
            //通过调用Introspector.getBeanInfo(c)方法可以获得BeanInfo对象,该对象封装了c类的所有属性
            beanInfo = Introspector.getBeanInfo(c);

        } catch (IntrospectionException e) {
            throw new SQLException(
                "Bean introspection failed: " + e.getMessage());
        }

        return beanInfo.getPropertyDescriptors();
    }

PropertyDescriptor[]是什么?看看Introspector.getBeanInfo(Tickets64.class)得到什么?

public class Tickets64 {

    private int id;

    private String stub;

    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getStub() {
        return stub;
    }

    public void setStub(String stub) {
        this.stub = stub;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
1.png

看完一目了然了吧

    protected int[] mapColumnsToProperties(ResultSetMetaData rsmd,
            PropertyDescriptor[] props) throws SQLException {

        int cols = rsmd.getColumnCount();
        int[] columnToProperty = new int[cols + 1];
        Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);

        for (int col = 1; col <= cols; col++) {
            String columnName = rsmd.getColumnLabel(col);
            if (null == columnName || 0 == columnName.length()) {
              columnName = rsmd.getColumnName(col);
            }
            String propertyName = columnToPropertyOverrides.get(columnName);
            if (propertyName == null) {
                propertyName = columnName;
            }
            for (int i = 0; i < props.length; i++) {

                if (propertyName.equalsIgnoreCase(props[i].getName())) {
                    columnToProperty[col] = i;
                    break;
                }
            }
        }
        return columnToProperty;
    }
    private <T> T populateBean(ResultSet rs, T bean,
            PropertyDescriptor[] props, int[] columnToProperty)
            throws SQLException {

        for (int i = 1; i < columnToProperty.length; i++) {

            if (columnToProperty[i] == PROPERTY_NOT_FOUND) {
                continue;
            }

            PropertyDescriptor prop = props[columnToProperty[i]];
            Class<?> propType = prop.getPropertyType();

            Object value = null;
            if(propType != null) {
                //获取数据库返回结果集中的一个字段对应的值
                value = this.processColumn(rs, i, propType);
                //如果数据库没有返回,则用默认值
                if (value == null && propType.isPrimitive()) {
                    value = primitiveDefaults.get(propType);
                }
            }
            //对应实体对象bean赋值对应属性
            this.callSetter(bean, prop, value);
        }

        return bean;
    }
 protected Object processColumn(ResultSet rs, int index, Class<?> propType)
        throws SQLException {

        Object retval = rs.getObject(index);
        if ( !propType.isPrimitive() && retval == null ) {
            return null;
        }
        /**
         * ServiceLoader<ColumnHandler> columnHandlers = ServiceLoader.load(ColumnHandler.class);
         * ServiceLoader会在包的META-INF得services文件夹下面寻找所有ColumnHandler相应类的实现
         */
        for (ColumnHandler handler : columnHandlers) {
            if (handler.match(propType)) {
                retval = handler.apply(rs, index);
                break;
            }
        }

        return retval;

    }
    private void callSetter(Object target, PropertyDescriptor prop, Object value)
            throws SQLException {

        Method setter = getWriteMethod(target, prop, value);

        if (setter == null || setter.getParameterTypes().length != 1) {
            return;
        }

        try {
            Class<?> firstParam = setter.getParameterTypes()[0];
            /**
             * ServiceLoader<PropertyHandler> propertyHandlers = ServiceLoader.load(PropertyHandler.class);
             * ServiceLoader会在包的META-INF得services文件夹下面寻找所有PropertyHandler相应类的实现
             */
            for (PropertyHandler handler : propertyHandlers) {
                //判断转换器是否可以转换
                if (handler.match(firstParam, value)) {
                    //转换成对应的值
                    value = handler.apply(firstParam, value);
                    break;
                }
            }

            // Don't call setter if the value object isn't the right type
            if (this.isCompatibleType(value, firstParam)) {
                setter.invoke(target, new Object[]{value});
            } else {
              throw new SQLException(
                  "Cannot set " + prop.getName() + ": incompatible types, cannot convert "
                  + value.getClass().getName() + " to " + firstParam.getName());
                  // value cannot be null here because isCompatibleType allows null
            }

        } catch (IllegalArgumentException e) {
            throw new SQLException(
                "Cannot set " + prop.getName() + ": " + e.getMessage());

        } catch (IllegalAccessException e) {
            throw new SQLException(
                "Cannot set " + prop.getName() + ": " + e.getMessage());

        } catch (InvocationTargetException e) {
            throw new SQLException(
                "Cannot set " + prop.getName() + ": " + e.getMessage());
        }
    }  

看其中一个转换器IntegerColumnHandler 实现

public class IntegerColumnHandler implements ColumnHandler {
    @Override
    public boolean match(Class<?> propType) {
        return propType.equals(Integer.TYPE) || propType.equals(Integer.class);
    }

    @Override
    public Object apply(ResultSet rs, int columnIndex) throws SQLException {
        return Integer.valueOf(rs.getInt(columnIndex));
    }
}

来看看META-INF.services下org.apache.commons.dbutils.ColumnHandler文件

org.apache.commons.dbutils.handlers.columns.StringColumnHandler
org.apache.commons.dbutils.handlers.columns.IntegerColumnHandler
org.apache.commons.dbutils.handlers.columns.BooleanColumnHandler
org.apache.commons.dbutils.handlers.columns.LongColumnHandler
org.apache.commons.dbutils.handlers.columns.DoubleColumnHandler
org.apache.commons.dbutils.handlers.columns.FloatColumnHandler
org.apache.commons.dbutils.handlers.columns.ShortColumnHandler
org.apache.commons.dbutils.handlers.columns.ByteColumnHandler
org.apache.commons.dbutils.handlers.columns.TimestampColumnHandler
org.apache.commons.dbutils.handlers.columns.SQLXMLColumnHandler

至此,DBUtils源码走完了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,500评论 18 399
  • JDBC概述 在Java中,数据库存取技术可分为如下几类:JDBC直接访问数据库、JDO技术、第三方O/R工具,如...
    usopp阅读 3,522评论 3 75
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,398评论 0 4
  • 知识是什么 经过实践证明、可以用来决策和行动的信息。 为什么学习知识 学习知识是为了我们能够工作、生活得更好、更幸...
    一个人的长途旅行阅读 199评论 0 1
  • 昨天,朋友找我聊天,说起旅行,聊到尼泊尔,我们侃侃而谈,意犹未尽。 于是,想着把自己在尼泊尔真真实实的经历都写出来...
    牛友果星球大萌阅读 6,864评论 72 233