解决模糊查询时输入%和__查询所有的情况

定义注解标记模糊查询的接口

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 标签全模糊查询的方法
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FullyFuzzyQueryMethod {
}

定义注解标记模糊查询的字段

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 标签全模糊查询的字段
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FullyFuzzyQueryField {
}

借助aop解决模糊查询字段转义

import com.netvine.patrolrobot.common.annotation.FullyFuzzyQueryField;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 解决模糊查询输入%和_查询所有的情况
 */
@Component
@Aspect
public class FullyFuzzyQueryAspect {

    @Pointcut("@annotation(com.netvine.patrolrobot.common.annotation.FullyFuzzyQueryMethod)")
    public void pointCut(){}


    @Before("pointCut()")
    public void before(JoinPoint joinPoint) throws IllegalAccessException {
        //获取请求参数
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            //获取字节码对象
            Class<?> aClass = arg.getClass();
            //获取所有属性
            Field[] fields = aClass.getDeclaredFields();
            for (Field field : fields) {
                //判断属性上面是否此注解
                FullyFuzzyQueryField fullyFuzzyQueryField = field.getAnnotation(FullyFuzzyQueryField.class);
                if (fullyFuzzyQueryField != null) {
                    //设置权限
                    field.setAccessible(true);
                    //获取属性值
                    Object value = field.get(arg);
                    if (Objects.nonNull(value)) {
                        String s = value.toString();
                        if (StringUtils.isNotBlank(s)) {
                            //将%和_转义
                            String newValue = s.replaceAll("%", "\\\\%").replaceAll("_", "\\\\_");
                            //修改属性值
                            field.set(arg,newValue);
                        }
                    }
                }
            }
        }
    }
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值