问题描述
当使用Mybatis 进行Page分页,再使用Page< map >作为接受参数。此时尝试修改map则会报错。
报错为
javascript
java.lang.UnsupportedOperationException: A TupleBackedMap cannot be modified
解决方案
使用新的数组,使用反射,构建工具类,自动将原值拷贝到对应的类上,完成转换。直接上代码
javascript
/**
* 用于解决mybatis 查询List<map>后无法修改的问题
* @author hh
* @date 2023/8/3
*/
public class MybatisMapUpdateUtils {
public static void main(String[] args) throws Exception {
Map<String,Object> map = new HashMap<>();
map.put("userName","吉吉强");
List<Map<String,Object>>list = new ArrayList<>();
list.add(map);
List<UserDto> object = (List<UserDto>) getObject(list, UserDto.class);
System.out.println(object);
}
public static Object getObject(List<Map<String,Object>>map, Class className) throws Exception {
List<Object> arrayList = new ArrayList<>();
for (Map<String,Object> vo: map){
Constructor constructors = className.getConstructor();
Object instance = constructors.newInstance();
for (String key:vo.keySet()){
System.out.println("key= "+key+" and value= "+vo.get(key));
try {
Field field = className.getDeclaredField(key);
field.setAccessible(true);
field.set(instance,vo.get(key));
} catch (Exception e){
System.out.println("field not found");
}
}
arrayList.add(instance);
}
return arrayList;
}
}
测试打印后,结果正常
javascript
key= userName and value= 吉吉强
[UserDto(userName=吉吉强)]
进程已结束,退出代码0