1.将Result封装成List,List中每个元素是一个Map,每个Map存一条记录,key为列名,value为其值。
public static List resultToList(ResultSet rs) throws java.sql.SQLException{
if(rs==null){
return null;
}
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
List list = new ArrayList();
Map rowData;
while (rs.next()){
rowData = new HashMap(columnCount);
for (int i=1; i<=columnCount; i++){
rowData.put(md.getColumnName(i),rs.getObject(i));
}
list.add(rowData);
}
return list;
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* <p>Title:属性封装类</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2008</p>
*
*/
public class BeanUtils {
/**
*
* @param bean 需要封装的vo
* @param map 需要转换的map
* @return 已经封装好数据的vo(object)
*/
public static Object MapToBean(Object bean, Map map) {
Map methods = new HashMap();
Method m[] = bean.getClass().getMethods();
for (int i = 0; i < m.length; i++) {
Method method = m[i];
String methodName = method.getName().toUpperCase();
methods.put(methodName, method);
}
Iterator it = null;
String key = "";
it = map.keySet().iterator();
while (it.hasNext()) {
key = (String) it.next();
String name = "GET" + key.toUpperCase();
if (methods.containsKey(name)) {
Method setMethod = (Method) methods.get("SET" + key.toUpperCase());
try {
if(setMethod!=null){
Object[] obj=null;
obj=new Object[1];
obj[0]=map.get(key);
setMethod.invoke(bean, obj);
}
else{
continue;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
return bean;
}
}
例如: List retultList=resultSetToList(resultset);
Student stu=(Student)BeanUtils.MapToBean(new Student(),(Map)retultList.get(0));