1. 程式人生 > >JDBC結果集工具類(resultSet轉list集合)

JDBC結果集工具類(resultSet轉list集合)


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.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JDBC結果集工具類
 * @author Administrator
 *
 */
public class JDBCResultUtil {
	private static Logger logger = LoggerFactory.getLogger(JDBCResultUtil.class);
	
	
	
	/**
	 * resultSet轉為list集合
	 * @param resultSet
	 * @param clazz
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 * @throws SQLException
	 * @throws IntrospectionException
	 */
	public static <T> List<T> resultToPojo(ResultSet resultSet,Class<T> clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException, IntrospectionException{
		ArrayList<T> arrayList = new ArrayList<T>();
			while(resultSet.next()){//遍歷resultset集合
				T newInstance = clazz.newInstance();
				BeanInfo beanInfo = Introspector.getBeanInfo(newInstance.getClass());
				PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
				int columnCount = resultSet.getMetaData().getColumnCount();//獲取總列數
				for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
					String name = propertyDescriptor.getName();//獲取屬性名稱
					Method writeMethod = propertyDescriptor.getWriteMethod();//獲取setter方法
					for(int i=1;i<=columnCount;i++){
						String columnName1 = resultSet.getMetaData().getColumnName(i);
						String columnName = resultSet.getMetaData().getColumnName(i);
						columnName=JDBCResultUtil.underLineToUpcase(columnName);
						if(columnName.equals(name)&&writeMethod!=null){
							writeMethod.invoke(newInstance, resultSet.getObject(columnName1));//物件屬性賦值
						}
					}
				}
				logger.info(newInstance.toString());
				arrayList.add(newInstance);
			}
			return arrayList;
	}
	
	/**
	 * 下劃線轉駝峰
	 * @param str 需要為純小寫
	 * @return
	 */
	public static String underLineToUpcase(String str){
		str = StringUtils.lowerCase(str);
		String[] split = str.split("_");
		StringBuilder stringBuilder = new StringBuilder(split.length);
		if(split!=null&&split.length>0){
			stringBuilder.append(split[0]);
			for(int j=1;j<split.length;j++){
				stringBuilder.append(JDBCResultUtil.firstToUp(split[j]));
			}
			
		}
		str=stringBuilder.toString();
		return str;
	}
	
	/**
	 * 首字母轉大寫
	 * @param str
	 * @return
	 */
	public static String firstToUp(String str){
		String replaceFirst = str.replaceFirst(str.substring(0,1), str.substring(0,1).toUpperCase());
		return replaceFirst;
	}
}