定义注解标记模糊查询的接口
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);
}
}
}
}
}
}
}