实现JDBC结果集的转换(ResultSet和List的转换)

public class DTOPopulator {
    public static List populate(ResultSet rs,Class clazz) throws Exception{
         ResultSetMetaData metaData = rs.getMetaData(); //取得结果集的元元素
        int colCount = metaData.getColumnCount();          //取得所有列的个数
         List ret = new ArrayList();                                       //存放返回结果的容器
         Field[] fields = clazz.getDeclaredFields();               //取得业务对象的属性
       
        while(rs.next()){
             Object newInstance = clazz.newInstance();   //构造业务对象实例
                            //将结果集中每一条记录,每一个字段取出,根据命名规则,对对应的业务对象的属性进行赋值
            for(int i=1;i<=colCount;i++){  //对于该记录的每一列
                try{
                     Object value = rs.getObject(i);
                    for(int j=0;j<fields.length;j++){
                         Field f = fields[j];
                        if(f.getName().equalsIgnoreCase(metaData.getColumnName(i).replaceAll("_",""))){
                             BeanUtils.copyProperty(newInstance,f.getName(),value);
                         }
                     }
                 }catch (Exception e) {
                    // TODO: handle exception
                     e.printStackTrace();
                 }
             }
             ret.add(newInstance);
         }
        return ret;
     }

 

你可能感兴趣的:(ResultSet)