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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
    * @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 @   liskov_design  阅读(82)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示