• 【spring data jpa】【mybatis】通过反射实现 更新/保存 实体的任意字段的操作


    代码如下:

    //代码示例:例如保存时,传入下面两个字段

    String filed;
    String content;

    //User代表要更新的实体,user即本对象
    //filed代表要更改的字段,例如user.name
    //content代表要更改字段的值,例如“张三”


    import
    org.springframework.beans.BeanUtils;

                             User user = new User();             
    //反射赋值 //反射 + javaBean机制 get set 方法 Class<? extends User> clz = user.getClass(); PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(clz, filed); //获取当前字段的javabean写方法 Method writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod != null) { try { writeMethod.invoke(user, "张三"); } catch (Exception e) { syatem.out.println(e); } }

    JPA保存即保存对象即可,因为对象的值已经存入user对象。

    User newUser = goodsMsgService.insert(oldGoodsMsg);

    mybatis保存对象:

    @Update("update goods_msg set ${filed} = #{context} where uid = #{uid}")
        public int saveFiled(@Param("filed")String filed, @Param("uid")String uid, @Param("context")String context);

    如下,有一个完整的代码示例可以参考:

    //将实体字段存入List
    
    public static final List<String> AUTH_FILEDS = Arrays.asList(new String[]{
                "innerFrist",
                "innerNormal", 
                "innerDanger", 
                "outFrist", 
                "outNormal", 
                "outDanger",
                "notAct", 
                "share",
                "notSub",
                "exceedMaxQueryTime",
                "scanCodeLimit",
                "innerSafetyTime",
                "outerSafetyTime",
                "scanCodeLimitTime"
        }); 
        
    
    
    //将实体属性  对应数据库字段存入 map 方便下面mybatis更新单个字段调用
        
        public static final Map<String,String> AUTH_FILEDS_MAPPING = new HashMap<>();
        
        static{
            AUTH_FILEDS_MAPPING.put("innerFrist","inner_frist");
            AUTH_FILEDS_MAPPING.put("innerNormal", "inner_normal");
            AUTH_FILEDS_MAPPING.put("innerDanger", "inner_danger");
            AUTH_FILEDS_MAPPING.put("outFrist", "out_frist");
            AUTH_FILEDS_MAPPING.put("outNormal", "out_normal");
            AUTH_FILEDS_MAPPING.put("outDanger", "out_danger");
            AUTH_FILEDS_MAPPING.put("notAct", "not_act");
            AUTH_FILEDS_MAPPING.put("share", "share");
            AUTH_FILEDS_MAPPING.put("notSub","not_sub");
            AUTH_FILEDS_MAPPING.put("exceedMaxQueryTime", "exceed_max_query_time");
            AUTH_FILEDS_MAPPING.put("scanCodeLimit","scan_code_limit");
            AUTH_FILEDS_MAPPING.put("innerSafetyTime","inner_safety_time");
            AUTH_FILEDS_MAPPING.put("outerSafetyTime","outer_safety_time");
            AUTH_FILEDS_MAPPING.put("scanCodeLimitTime","scan_code_limit_time");
        }
        
        
        /**
         * 保存或修改(针对单一字段)
         * 
         * ===========================非空字段===========================
         * [
         *     要修改的字段 : filed
         *     字段内容 : context
         *     是否全局 : global (1全局  0不是全局)
         *     绑定的商品或分类 : guid(全局为空)
         * ]
         * ===========================保存逻辑===========================
         *         1 检查要修改的字段是否存在
         *         2 判断操作话述是否属于当前租户
         *         3 判断是否是全局,不是全局guid做非空验证
         *         4 如果已经存在记录则修改   如果不存在新增
         * 
         * ===========================安全验证===========================
         * guid是否属于当前租户
         * 
         * 
         */
        @Override
        public AjaxResult<String> saveFiled(@RequestBody SaveFiledRequestBean requestBean) {
            //当前租户
            TenementUser tenementUser = RequestData.TENEMENT_USER.get();
            
            //非空
            LunaResultBean.checkField(requestBean,"filed","context","global","name");
            
            // 不是全局的非空
            if (1 != requestBean.getGlobal()) {
                LunaResultBean.checkField(requestBean,"guid");
            }
            
            String filed = requestBean.getFiled();
            String guid = requestBean.getGuid();
            String context = requestBean.getContext();
            
            AjaxResult<String> res = new AjaxResult<String>();
            
            boolean isAdd = true;
            boolean success = true;
            GoodsMsg oldGoodsMsg = null;
            if(AUTH_FILEDS.contains(filed)){
                
                if (StringUtils.isNotBlank(guid)) {
                
                    boolean check = goodsConfigUtils.check(GoodsConfigUtils.CHECK_GUID, guid);
                    if (check) {
                        
                        // 是否需要新增
                        oldGoodsMsg = goodsMsgService.findByGuid(guid);
                        
                        if (oldGoodsMsg != null) {
                            isAdd = false;
                            
                        }
                        
                    } else {
                        success = false;
                    }
                    
                } else {
                    // 判断全局是否已经存在
                    oldGoodsMsg = goodsMsgService.findByGlobalMsg(tenementUser.getTenementId());
                    if (oldGoodsMsg != null) {
                        
                        isAdd = false;
                    }
                    
                }
                
                //判断参数验证是否通过
                if (success) {
                    if (isAdd) {
                        // 添加
                        oldGoodsMsg = new GoodsMsg();
                        oldGoodsMsg.initInsertData();
                        oldGoodsMsg.setUid(UUID.randomUUID().toString().replaceAll("-", ""));
                        oldGoodsMsg.setGuid(guid);
                        oldGoodsMsg.setGlobal(requestBean.getGlobal());
                        
                        //反射赋值
                        //反射 + javaBean机制 get set 方法
                        Class<? extends GoodsMsg> clz = oldGoodsMsg.getClass();
                        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(clz, filed);
                        
                        //获取当前字段的javabean写方法
                        Method writeMethod = propertyDescriptor.getWriteMethod();
                        if (writeMethod != null) {
                            try {
                                writeMethod.invoke(oldGoodsMsg, requestBean.getContext());
                            } catch (Exception e) {
                                throw new LunaException("方法 "+ writeMethod.getName() +"无法执行",AjaxResult.ERROR_SYS_EXCPTION);
                            }
                        }
                        
                        //新增
                        GoodsMsg insert = goodsMsgService.insert(oldGoodsMsg);
                        if (insert != null) {
                            res.initTrue("操作成功");
                        } else {
                            res.initFalse("操作失败", LunaResultBean.ERROR_BUSINESS);
                        }
                        
                    } else {
                        //修改
                        //调用mybatis   update 字段 by uid
                        int saveFiled = goodsMsgService.saveFiled(AUTH_FILEDS_MAPPING.get(filed), oldGoodsMsg.getUid(), context);
                        
                        if(saveFiled > 0){
                            res.initTrue("操作成功");
                        } else {
                            res.initFalse("操作失败", LunaResultBean.ERROR_BUSINESS);
                        }
                    }
                    
                } else {
                    res.initFalse("请选择正确的商品或商品类型", LunaResultBean.ERROR_BUSINESS);
                }
                
            }else{
                res.initFalse("无效字段 ["+ filed +"]", LunaResultBean.ERROR_BUSINESS);
            }
            
            return res;
        }
    View Code
  • 相关阅读:
    剑指63.数据流中的中位数
    剑指62.二叉搜索树的第k个结点
    JPA ---- EntityManager使用
    JPA ---- EntityManager介绍
    win10多桌面切换
    $emit子组件如何传递多个参数
    height高度自适应
    vue Avoided redundant navigation to current location
    Ant Design 使用小结
    Object.keys方法之详解
  • 原文地址:https://www.cnblogs.com/sxdcgaq8080/p/9118665.html
Copyright © 2020-2023  润新知