/** * @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; }