問題背景 使用mybatis-plus進行資料庫交互,預設開啟null不更新設置,在新增數據後,編輯頁面將欄位值清除後(date類型,int類型,為避免預設值傳入,model全部使用包裝類型初始化為null)無法將null值更新至資料庫 單個解決方案 通過UpdateWrapper的set方法強制字 ...
問題背景
使用mybatis-plus進行資料庫交互,預設開啟null不更新設置,在新增數據後,編輯頁面將欄位值清除後(date類型,int類型,為避免預設值傳入,model全部使用包裝類型初始化為null)無法將null值更新至資料庫
單個解決方案
通過UpdateWrapper的set方法強制欄位為null值
通用解決方法
定義基礎類BaseModel,增加屬性updateFieldList,model繼承此類
public class BaseModel { @TableField(exist = false) @JSONField(serialize = false) private List<String> updateFieldList; public List<String> getUpdateFieldList() { return updateFieldList; } public void setUpdateFieldList(List<String> updateFieldList) { this.updateFieldList = updateFieldList; } }
自定自定義註解UpdateRequestBody替代RequestBody
@ResponseBody @PostMapping("/update") public Object update(@UpdateRequestBody AccountDO entity) { Result result = null; try { accountService.update(entity); result = Result.okResult(); } catch (Exception e) { result = Result.errorResult(); } return result; } @ResponseBody @PostMapping("/batchUpdate") public Object batchUpdate(@UpdateRequestBody List<AccountDO> entityList) { Result result = null; try { accountService.batchUpdate(entityList); result = Result.okResult(); } catch (Exception e) { result = Result.errorResult(); } return result; }
自定義HandlerMethodArgumentResolver對前臺json至後臺Model轉換的攔截,需要對List類型的Model集合進行支持,獲取前臺提交json對應定義Model中有同名屬性的,進行加入打待更新欄位列表updateFieldList
public class BaseModelMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) { if (methodParameter.hasParameterAnnotation(UpdateRequestBody.class)) { //集合 if(List.class.isAssignableFrom(methodParameter.getParameterType())){ ParameterizedType parameterizedType = (ParameterizedType) methodParameter.getGenericParameterType(); Class clazz = (Class)parameterizedType.getActualTypeArguments()[0]; //取出List中的真實對象類型 if(BaseModel.class.isAssignableFrom(clazz)){ return true; }else{ return false; } }else{ //單個對象 if(BaseModel.class.isAssignableFrom(methodParameter.getParameterType())){ return true; }else{ return false; } } } return false; } @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { String body = ""; try { HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class); body = CommonUtil.getBodyString(request); } catch (Exception e) { e.printStackTrace(); } if(List.class.isAssignableFrom(methodParameter.getParameterType())){ List resultList = new ArrayList(); ParameterizedType parameterizedType = (ParameterizedType) methodParameter.getGenericParameterType(); Class clazz = (Class)parameterizedType.getActualTypeArguments()[0]; List<Field> fs = Arrays.asList(clazz.getDeclaredFields()); JSONArray array = JSONArray.parseArray(body); for (Object temp:array) { JSONObject obj = JSONObject.parseObject(temp.toString()); List<String> updateFieldList = new ArrayList<>(); for (String key : obj.keySet()) { for (Field filed : fs) { if (key.toLowerCase().equals(filed.getName().toLowerCase())) { updateFieldList.add(key.toLowerCase()); continue; } } } obj.put("updateFieldList",updateFieldList); resultList.add(obj); } return JSONArray.parseArray(resultList.toString(),clazz); }else{ Class clazz = methodParameter.getParameterType(); List<String> updateFieldList = new ArrayList<>(); List<Field> fs = Arrays.asList(clazz.getDeclaredFields()); JSONObject obj = JSON.parseObject(body); for (String key : obj.keySet()) { for (Field filed : fs) { if (key.toLowerCase().equals(filed.getName().toLowerCase())) { updateFieldList.add(key.toLowerCase()); continue; } } } obj.put("updateFieldList",updateFieldList); return JSON.parseObject(obj.toString(),clazz); } } }
將自定義BaseModelMethodArgumentResolver 加入到配置中去
public class WebConfig implements WebMvcConfigurer { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(new BaseModelMethodArgumentResolver()); } }
進行自定義UpdateWrapper構造
public <T extends BaseModel> UpdateWrapper getUpdateWrapper(T entity){ UpdateWrapper<T> updateWrapper = new UpdateWrapper<T>(); try{ Class clazz = entity.getClass(); List<Field> fs = Arrays.asList(clazz.getDeclaredFields()); List<String> updateFieldList = entity.getUpdateFieldList(); if(updateFieldList!=null){ for (String updateFiled:updateFieldList ) { for (Field field:fs) { field.setAccessible(true); if(field.getName().toLowerCase().equals(updateFiled)){ Object fieldValue = field.get(entity); updateWrapper.set(fieldValue==null,field.getName(),null); continue; } } } } return updateWrapper; }catch (Exception e){ e.printStackTrace(); } return updateWrapper; }
註:對標記TableField忽略註解的欄位可以優化,反射可以應用初始化時掃描加入緩存進行優化