Mybatis Plus根据传入的对象查询

上util代码

private static Pattern humpPattern = Pattern.compile("[A-Z]");

    public static<T> void notNullField(T T, QueryWrapper<T> wrapper){
        for (Field field : T.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                //序列化 字段不需要查询
                if("serialVersionUID".equals(field.getName())){
                    continue;
                }
                //属性为空,不用查询
                if(field.get(T) == null){
                    continue;
                }
                //主键 注解TableId
                TableId tableId = field.getAnnotation(TableId.class);
                if (tableId != null){
                    //主键
                    wrapper.eq(tableId.value(),field.get(T));
                    continue;
                }
                //数据库中字段名和实体类属性不一致 注解TableField
                TableField tableField = field.getAnnotation(TableField.class);
                if(tableField != null){
                    if(tableField.exist()){
                        wrapper.eq(tableField.value(),field.get(T));
                    }// @TableField(exist = false) 不是表中内容 不形成查询条件
                    continue;
                }
                //数据库中字段名和实体类属性一致
                wrapper.eq(humpToLine(field.getName()),field.get(T));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

humpToLine(field.getName())

这个的作用是把驼峰转为下滑线,按命名规范,根据对象查询时,对象的属性都是驼峰形式的,查询的时候,要转为数据库中的下划线格式

应用示例

        QueryWrapper<AlarmDeviceConfig> wrapper = new QueryWrapper<>();

        AlarmDeviceConfig alarmDeviceConfig = new AlarmDeviceConfig();

        BeanCopyUtil.copyProperties(queryAlarmDeviceConfigParam, alarmDeviceConfig);

        MybatisPlusUtil.notNullField(alarmDeviceConfig,wrapper);

        List<AlarmDeviceConfig> alarmDeviceConfigList = deviceConfigMapper.selectList(wrapper);

这个是应用的示例,仅供参考

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值