一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ORM小工具

时间:2022-07-02 17:42:05 编辑:袖梨 来源:一聚教程网

ORM小工具

代码:

package org.blueidea.tools;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
* ResultSetMetaData 可用于获取关于 ResultSet 对象中列的类型和属性信息的对象
* ResultSet.getMetaData()  检索此 ResultSet 对象的列的编号、类型和属性
*/
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                         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;
    }
}

热门栏目