本文主要是介绍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方法 方法名大小写不限
转自:http://hfkiss44.iteye.com/blog/568525
这篇关于JDBC:如何将resultset的信息自动封装到pojo里面的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!