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<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;
}
}