[Java 基础]ResultSet 指定field映射到Pojo对象的Map
现在有一个需求,mysql查询记录映射到List<pojo>中,其中pojo某个字段是Map类型,需要将查询记录中这列映射到Map中,否则默认会当作String映射,以下为当前代码:
public List<T> mapRersultSetToObject(ResultSet rs, Class outputClass) { List<T> outputList = null; try { // make sure resultset is not null if (rs != null) { // check if outputClass has 'Entity' annotation if (outputClass.isAnnotationPresent(Entity.class)) { // get the resultset metadata ResultSetMetaData rsmd = rs.getMetaData(); // get all the attributes of outputClass Field[] fields = outputClass.getDeclaredFields(); while (rs.next()) { T bean = (T) outputClass.newInstance(); for (int _iterator = 0; _iterator < rsmd.getColumnCount(); _iterator++) { // getting the SQL column name String columnName = rsmd.getColumnName(_iterator + 1); // reading the value of the SQL column Object columnValue = rs.getObject(_iterator + 1); // iterating over outputClass attributes to check if // any attribute has 'Column' annotation with // matching 'name' value for (Field field : fields) { if (field.isAnnotationPresent(Column.class)) { Column column = field.getAnnotation(Column.class); if (column.name().equalsIgnoreCase(columnName) && columnValue != null) { BeanUtils.setProperty(bean, field.getName(), columnValue); break; } } } } if (outputList == null) { outputList = new ArrayList<T>(); } outputList.add(bean); } } else { // throw some error } } else { return null; } }
解决方案,如果设置属性时每次都检查字段类型,效率会比较低,通过发生异常捕获,然后再转化的方式,如下代码所示:
if (column.name().equalsIgnoreCase(columnName) && columnValue != null) { try{ BeanUtils.setProperty(bean, field.getName(), columnValue); }catch (ConversionException exception){ if(field.getType().equals(Map.class)){ BeanUtils.setProperty(bean, field.getName(), JSON.parse(String.valueOf(columnValue))); } } break; }
欢迎关注Java流水账公众号