提高效率一直是個永恆的話題,編程中有一項也是可以提到效率的,那就是專注做一件事情,讓其它沒有強緊密聯系的與之分開。這裡分享下我們做CRUD時遇到的常見數據處理場景:
優點:
缺點:
上面關於默認值與null語義問題不需要解決,因為我們認為具有默認值帶來的優點遠大於可空字段帶來的煩惱,我們來看默認值與系統字段一般情況下如何處理:
public static <T> void emptyNullValue(final T model) { Class<?> tClass = model.getClass(); List<Field> fields = Arrays.asList(tClass.getDeclaredFields()); for (Field field : fields) { Type t = field.getType(); field.setAccessible(true); try { if (t == String.class && field.get(model) == null) { field.set(model, ""); } else if (t == BigDecimal.class && field.get(model) == null) { field.set(model, new BigDecimal(0)); } else if (t == Long.class && field.get(model) == null) { field.set(model, new Long(0)); } else if (t == Integer.class && field.get(model) == null) { field.set(model, new Integer(0)); } else if (t == Date.class && field.get(model) == null) { field.set(model, TimeHelper.LocalDateTimeToDate(java.time.LocalDateTime.of(1990, 1, 1, 0, 0, 0, 0))); } } catch (IllegalAccessException e) { e.printStackTrace(); } } }
然後在代碼調用insert前調用函數來解決:
ModelHelper.emptyNullValue(request);
如何處理系統字段呢,在創建編輯數據時,需要獲取當前用戶,然後根據邏輯分別更新創建人信息以及編輯人信息,我們專門編寫一個反射機制的函數來處理系統字段:
注:下面的系統字段的識別,是靠系統約定實現的,比如creator約定為創建人等,可根據不同的情況做數據兼容,如果系統設計的好,一般在一個系統下所有表的風格應該是相同的。
public static <T> void buildCreateAndModify(T model,ModifyModel modifyModel,boolean isCreate){ Class<?> tClass = model.getClass(); List<Field> fields = Arrays.asList(tClass.getDeclaredFields()); for (Field field : fields) { Type t = field.getType(); field.setAccessible(true); try { if(isCreate){ if (field.getName().equals(modifyModel.getcId())) { field.set(model, modifyModel.getUserId()); } if (field.getName().equals(modifyModel.getcName())) { field.set(model, modifyModel.getUserName()); } if (field.getName().equals(modifyModel.getcTime())) { field.set(model, new Date()); } } if (field.getName().equals(modifyModel.getmId())) { field.set(model, modifyModel.getUserId()); } if (field.getName().equals(modifyModel.getmName())) { field.set(model, modifyModel.getUserName()); } if (field.getName().equals(modifyModel.getmTime())) { field.set(model, new Date()); } } catch (IllegalAccessException e) { e.printStackTrace(); } } }
最後在數據處理前,根據創建或者編輯去調用函數來給系統字段賦值,這類代碼都混雜在業務代碼中。
ModifyModel modifyModel = new ModifyModel(); modifyModel.setUserId(getCurrentEmployee().getId()); modifyModel.setUserName(getCurrentEmployee().getName()); if (request.getId() == 0) { ModelHelper.buildCreateAndModify(request, modifyModel, true); deptService.insert(request); } else { ModelHelper.buildCreateAndModify(request, modifyModel, false); deptService.updateByPrimaryKey(request); }
我們可以利用參數注入來解決。參數注入的理念就是在spring mvc接收到前台請求的參數後,進一步對接收到的參數做處理以達到預期的效果。我們來創建ManageModelConfigMethodArgumentResolver,它需要實現HandlerMethodArgumentResolver,這個接口看起來比較簡單,包含兩個核心方法:
@Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(ManageModelConfig.class); }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object manageModel =getRequestResponseBodyMethodProcessor().resolveArgument(parameter, mavContainer, webRequest, binderFactory); ServletRequest servletRequest = webRequest.getNativeRequest(ServletRequest.class); Employee currentUser = (Employee) servletRequest.getAttribute(DEFAULT_ATTRIBUTE_GET_USER_FROM_REQUEST); if (null == currentUser) { return manageModel; } ManageModelConfig parameterAnnotation = parameter.getParameterAnnotation(ManageModelConfig.class); ModelHelper.setDefaultAndSystemFieldsValue(manageModel, currentUser,parameterAnnotation.isSetDefaultFieldsValue()); return manageModel; }
這段函數有幾處核心邏輯:
private RequestMappingHandlerAdapter requestMappingHandlerAdapter=null; private RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor = null; private RequestResponseBodyMethodProcessor getRequestResponseBodyMethodProcessor() { if(null==requestMappingHandlerAdapter) { requestMappingHandlerAdapter=new RequestMappingHandlerAdapter(); } if (null==requestResponseBodyMethodProcessor) { List<HttpMessageConverter<?>> messageConverters = requestMappingHandlerAdapter.getMessageConverters(); messageConverters.add(new MappingJackson2HttpMessageConverter()); requestResponseBodyMethodProcessor = new RequestResponseBodyMethodProcessor(messageConverters); } return requestResponseBodyMethodProcessor; }
通過如下代碼就可以取到參數對象了,其實就是讓spring mvc重新解析了一遍參數。
Object manageModel =getRequestResponseBodyMethodProcessor().resolveArgument(parameter, mavContainer, webRequest, binderFactory);
ServletRequest servletRequest = webRequest.getNativeRequest(ServletRequest.class); Employee currentUser = (Employee) servletRequest.getAttribute(DEFAULT_ATTRIBUTE_GET_USER_FROM_REQUEST);
ManageModelConfig parameterAnnotation = parameter.getParameterAnnotation(ManageModelConfig.class); ModelHelper.setDefaultAndSystemFieldsValue(manageModel, currentUser,parameterAnnotation.isSetDefaultFieldsValue());
最後將我們的參數注入邏輯啟動起來,這裡選擇在xml中配置:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"> <mvc:argument-resolvers> <bean class="cn.wanmei.party.management.common.mvc.method.annotation.ManageModelConfigMethodArgumentResolver"/> </mvc:argument-resolvers> </mvc:annotation-driven>
再看action中的調用:只需要在參數前面增加注解@ManageModelConfig,如果需要處理默認值,則將啟用默認值的選項設置成true即可,下面的實現部分完全看不到任何與業務無關的代碼。
@RequestMapping(value = "/addOrUpdateUser") @ResponseBody public Map<String, Object> addOrUpdateUser(@ManageModelConfig(isSetDefaultFieldsValue=true) EmployeeDto request) { Map<String, Object> ret = new HashMap<>(); ValidateUtil.ValidateResult result= new ValidateUtil().ValidateModel(request); boolean isCreate=request.getId() == 0; try { if (isCreate) { employeeService.insert(request); } else { employeeService.updateByPrimaryKey(request); } ret.put("data", "ok"); }catch (Exception e){ ret.put("err", e.getMessage()); } return ret; }
通過自定義實現HandlerMethodArgumentResolver,來捕獲ajax請求的參數,利用反射機制動態的將系統字段以及需要處理默認值的字段自動賦值,避免人工干預,起到了代碼精簡,邏輯干淨,問題統一處理的目的。需要注意的是這些實現都是結合當前系統設計的,比如我們認為id字段>0就代表是更新操作,為空或者等於小於0就代表是創建,系統字段也是約定名稱的等等。