dbutils的使用研究

最近在研究公司前辈写的基于dbutils的查询.有些感觉不错,记录一下
public abstract class BaseDao <T>{
	
	protected QueryRunner queryRunner = new QueryRunner(getDataSource());	
	
	protected ResultSetHandler<T> defaultResultSetHandler = 
		new BeanHandler<T>(getEntityClass(),new BasicRowProcessor(new MyBeanProcessor()));
	
	protected ResultSetHandler<List<T>> defaultListHandler = 
		new BeanListHandler<T>(getEntityClass(),new BasicRowProcessor(new MyBeanProcessor()));
	
	protected MapHandler mapHandler = new MapHandler();
	
	protected abstract Class getEntityClass();
	
	protected MapListHandler mapListHandler = new MapListHandler();
	
    public DataSource getDataSource(){
    	return DataSourceFactory.getInstance().getDataSource();
    }
    public DataSource getDataSource(String name){
    	return DataSourceFactory.getInstance().getDataSource(name);
    }

 先看第7行加粗部分(sorry 这厮没给俺加粗)

protected ResultSetHandler<T> defaultResultSetHandler = 
		new BeanHandler<T>(getEntityClass(),new BasicRowProcessor(new MyBeanProcessor()));

 .BasicRowProcessor类,是一个内容转换的类,也就是把数据转成getEntityClass()方法返回的class类型,

protected Class getEntityClass() {
	return Map.class;
}

  根据它的api可知,

BasicRowProcessor(BeanProcessor convert) 
          BasicRowProcessor constructor.

可以传一个自定义的processor来转换查询内容的格式.

如下边我贴这个,其实就是拿的官方BeanProcessor.java源码.只是加了72行的转换.

String propertyName = underScore2CamelCase(columnName);

将oracle数据表中字段带下划线的去掉.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inspur.base;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.BeanProcessor;
import org.loushang.next.chart.ChartData;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

/**
 * <p>
 * <code>BeanProcessor</code> matches column names to bean property names
 * and converts <code>ResultSet</code> columns into objects for those bean
 * properties.  Subclasses should override the methods in the processing chain
 * to customize behavior.
 * </p>
 *
 * <p>
 * This class is thread-safe.
 * </p>
 *
 * @see BasicRowProcessor
 *
 * @since DbUtils 1.1
 */
public class MyBeanProcessor extends BeanProcessor{

    
    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 = underScore2CamelCase(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;
    }

    /** 
     * @param strs 
     *        待转化字符串 
     * @return 
     * @author estone 
     * @description 下划线格式字符串转换成驼峰格式字符串 
     *              eg: player_id -> playerId;<br> 
     *              player_name -> playerName; 
     */  
    public String underScore2CamelCase(String strs) {  
    	StringBuffer sb= new StringBuffer();
        String[] elems = strs.split("_");  
        for ( int i = 0 ; i < elems.length ; i++ ) {  
            elems[i] = elems[i].toLowerCase();  
            if (i != 0) {  
                String elem = elems[i];  
                char first = elem.toCharArray()[0];  
                if(Character.isLetter(first)){
                	elems[i] = "" + (char) (first - 32) + elem.substring(1);  
                }
                
            } 
            sb.append(elems[i]);
        }  
        return sb.toString();  
    }  

}

猜你喜欢

转载自xiaosheng12345.iteye.com/blog/2001369