數據庫歷史多條記錄變更通過反射回寫主表案例

 /**
     *@Author: yitianRen
     *@Date: 13:56 2020/2/12
     *@Description: 回寫主表 根據idNum
     *@Version v1.0
     */
    private void writeBackeAmBaseInfo(String idNum,List<AmBaseInfoChgItem> amBaseInfoChgItems) {
        try {
            //遍歷更改
            if(!CollectionUtils.isEmpty(amBaseInfoChgItems)){
                //操作實體
                AmBaseInfo amBaseInfo=new AmBaseInfo();
                Field[] fields = AmBaseInfo.class.getDeclaredFields();
                Map<String,Object> fidldValMap = new HashMap<>();
                for (AmBaseInfoChgItem amBaseInfoChgItem : amBaseInfoChgItems) {
                    //枚舉類特殊處理
                    if("adminPost".equals(amBaseInfoChgItem.getItemField())){
                        fidldValMap.put(amBaseInfoChgItem.getItemField(), AdminPost.valueOf(amBaseInfoChgItem.getItemValueNew()));
                    }else if ("acntWorkYear".equals(amBaseInfoChgItem.getItemField())) {
                        fidldValMap.put(amBaseInfoChgItem.getItemField(), new BigDecimal(amBaseInfoChgItem.getItemValueNew()));
                    }else{
                        fidldValMap.put(amBaseInfoChgItem.getItemField(), amBaseInfoChgItem.getItemValueNew());
                    }
                }
                //反射賦值
                for (Map.Entry<String, Object> entry : fidldValMap.entrySet()) {
                    for (Field field : fields) {
                        if (field.getName().equals(entry.getKey())) {
                            field = AmBaseInfo.class.getDeclaredField(field.getName());
                            //私有值可注入
                            field.setAccessible(true);
                            field.set(amBaseInfo, entry.getValue());
                        }
                    }
                }
                amBaseInfo.setIdNum(idNum);
                amBaseInfoMapper.updateByPrimaryKeySelective(amBaseInfo);
            }
        }catch (Exception e){
            throw new RuntimeException("回寫主表失敗"+e);
        }

    }

思考:如果實體類中枚舉類型過多,是不是需要些很多判斷?其實是有優化方案的,這裏給個思路和部分代碼

判斷實體類中是否是枚舉類,如果是枚舉就通過枚舉類型和值獲取到響應的枚舉然後反射寫給主表

用到的util和其他內容在另一篇博客EnumUtil通過枚舉類型和相應的值返回枚舉And轉換枚舉到JSONArray

 if(BaseEnum.class.isAssignableFrom(f.getType())){//枚舉類型
                                //前端傳遞過來的變更項彙總列表中變更前、後的值是code,人員信息實體中是枚舉類型,需要轉換一下
                                f.set(baseInfo,EnumUtil.codeOf(f.getType(),newValue));
                            }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章