Java.getListTBySql.sql查询结果直接转为List<T>结果

 /**
     * @Description: * sql查询结果直接转为List<T>结果
     * * 该sql语句和Bean里面的属性是区分大小写的,所以尽量保持一致【要么大写】,【要么小写】
     * @author: xxxxxx
     * @date 2013/4/27 17:53
     */
    @Override
    public <T> List<T> getListTBySql(String sql, Class<T> beanClass) {
        List<Map<String, Object>> mapList = this.getListMapBySql(sql);
        if (mapList.size() == 0) {
            return new ArrayList<>();
        }

        List<T> list = new ArrayList<T>();
        Field[] fields = beanClass.getDeclaredFields();
        String propertyName;
        Map<String, Object> hashMap;

        for (int i = 0; i < mapList.size(); i++) {
            if (fields == null || fields.length == 0) {
                break;
            }
            hashMap = new TreeMap<>();
            Object obj = null;
            try {
                obj = Class.forName(beanClass.getName()).newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            for (Field field : fields) {
                propertyName = field.getName();
                /**
                 * 如果数据库查询返回的属性keys集合map不包含属性名称-》则赋值为空
                 * else -》 赋值对应的数据库值
                 */
                if (mapList.get(i).containsKey(propertyName)) {
                    hashMap.put(propertyName, mapList.get(i).get(propertyName));
                } else {
                    hashMap.put(propertyName, null);
                }
            }
            try {
                BeanUtils.populate(obj, hashMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            list.add((T) obj);
        }

        return list;
    }

  

posted @ 2023-01-13 16:58  liskov_design  阅读(68)  评论(0编辑  收藏  举报