针对jdbc编程 如何将resultset的信息自动封装到pojo里面

不多说了 直接上代码

public static List resultSetToList(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;
}


首先将ResultSet封装成list 而每条记录对应一个实体Map

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作为参数 然后再将其list里面的map转换成相对性的pojo

假设查询的是student表 与之对应的pojo是Student类 那么调用方法如下:

首先查询数据 获取到resultset
然后
List retultList=resultSetToList(resultset);
遍历retultList 将list里面的Map都转换成pojo
Student stu=(Student)BeanUtils.MapToBean(new Student(),(Map)retultList.get(0));

注意:查询出来的字段名要和pojo中的属性名相同 若查询出age字段 pojo中需有getAge和setAge方法 方法名大小写不限

每天记录一点 好记星不如烂笔头
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值