反射动态操作数据实体类并修改为某个值

之前写了一篇博客说是想动态查询某个字段,但是$存在sql注入问题。所以现在用另一种方式解决。

因为之前业务是把某id对应条数下面一个属性值置位null并在数据库中修改。所以必须写 stringValue = “”;。如果是修改为别的值则直接
stringValue 放到中就行。

field.set(stationInforationCheckDropDown,stringValue); 

实际代码:

 @Override
    public int deleteAssertDropResult(String name, String nameziduan,Integer integer, String stringValue) {
        stringValue = "";
        Field field = null;
        List list = new ArrayList<>();
        try {
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("id",integer);
            StationInforationCheckDropDown stationInforationCheckDropDown = assertDropDao.selectOne(wrapper);
            String fieldValueByName = (String)getFieldValueByName(name, stationInforationCheckDropDown);
            //判断该属性对应的值在大表中是否存在,如果存在则不能删除,否则可以删除
            // String stringDaName = assertService.selectChecDakByName(name,stringName);
            QueryWrapper wrapperDa= new QueryWrapper<>();
            wrapperDa.eq(nameziduan,fieldValueByName);
            List stationInforationChecks = assertDao.selectList(wrapperDa);
            for (StationInforationCheck stationInforationCheck : stationInforationChecks) {
                String stringDaName = (String)getFieldValueByName(name, stationInforationCheck);
                if (StringUtils.isNotBlank(stringDaName)){
                    return 0;
                }
            }
            field = StationInforationCheckDropDown.class.getDeclaredField(name);
            field.setAccessible(true);
            field.set(stationInforationCheckDropDown,stringValue);
            return assertDropDao.updateById(stationInforationCheckDropDown);
        } catch (Exception e) {
            log.error("修改下拉属性值为null失败");
        }
        return 0;
    }

根据属性名获取属性值

 /* 根据属性名获取属性值  fieldName:属性名   o: 对象
     * */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {

            return null;
        }
    }

你可能感兴趣的:(mybatis,工具类)