mybatis like 的坑

时间:2021-03-25 17:33:04

昨天快要下班的时候组长交代了一个任务,说起来很简单,是这样的:

  系统里面有一个字段为name,这个name允许设置为特殊字符,目前根据name模糊匹配,如果遇到特殊字符 比如 "$" , "%", "_", "\"等字符就会查询不到或者报错,需要解决此问题。

之前是写了一个工具类来处理此问题,工具类如下:

public static String escapseSpecialChar(String query) {
  if (StringUtils.isNotBlank(query)) {
  query = query
        .replaceAll("\\\\", "\\\\\\\\\\\\\\\\")
        .replaceAll("%", "\\\\%");
  }
  return query;
}

这里面只处理了‘\’ 和‘%’,但是处理的结果不正确

1. 为什么 replaceAll("\\\\", "\\\\\\\\\\\\\\\\") 第一个参数是四个 ‘ \ ’ ?

  replaceAll 第一个参数需要时一个正则表达式,在正则表达式中的“\”表示和后面紧跟着的那个字符构成一个转义字符,代表着特殊的意义;所以如果你要在正则表达式中表示一个反斜杠\,应当写成“\\”。因为在正则要经过两次转义,因此就需要四个反斜杠才可以匹配一个反斜杠。Java先转义成“\”,在由正则进行一次转义,就结果就为“\”。

一句话:表示正则表达式里面的斜杠“\”,然后再用字符串表示出来。而这2个斜杠分别需要一个转义符,这样就成了4个斜杠在正则表达式里面表示一个斜杠。

下面代码示例:

//将会报错,你应当这样写Matcher m =
Matcher m = Pattern.compile(“\\”).matcher(“\\”);
//这才是正确且匹配的
Pattern.compile(“\\\\”).matcher(“\\”)来:

我们来看一下String类两个方法:

a)replace(CharSequence target,CharSequence 
b)replacement)replaceAll(String regex, String replacement)

public static void main(String[] arg) throws OgnlException {
String s ="abcd\\123\\\\dcba";
//把s中的反斜杠\ 替换为\\
System.out.println(s);
//结果是abcd\\123\\\\dcba,记住\\\\表示\
System.out.println(s.replaceAll("\\\\", "\\\\\\\\"));
//结果是abcd\\\\123\\\\\\\\dcba
System.out.println(s.replace("\\", "\\\\\\\\"));
}

2.  为什么 replaceAll 中的第二个参数为16个反斜杠依然没有办法实现

  同1,四个反斜杠代表的其实是一个反斜杠,在那么也就是说,如果我的 sql 需要写成  select name from table where name like '%\\\\%'  , 那么,我需要将一个反斜杠转为四个反斜杠,讲道理,需要16个反斜杠就好了,但是为什么没有成功呢,还是同样的道理,被转义了,比如两个反斜杠代表其实是一个反斜杠字符,那么也就是说我如果要给sql传过去四个反斜杠字符,那么我每一个反斜杠字符需要用八个反斜杠来表示,所以,其实将 replaceAll 中第二个参数改为32个反斜杠就可以了

看一下我最后修改的结果

public static String escapseSpecialChar(String query) {
  if (StringUtils.isNotBlank(query)) {
  query = query
        .replaceAll("/", "//")
        .replaceAll("\\\\", "/\\\\")
        .replaceAll("%", "/%")
        .replaceAll("_", "/_");
  }
  return query;
}

3. 修改后的代码:第一步将传过来的 ' / ' 转为 ' // ' 两个斜杠,然后将所有需要转义的特殊字符转多加一个斜杠 ' / ' ,这样做是因为mysql有一个 ESCAPE 的用法,具体用法如下:

  SELECT * FROM table WHERE `name` LIKE '%/_%' ESCAPE '/' ;

 本来下划线 '_' 在mysql是一个通配符,匹配一个字符,但是 使用 ESCAPE '/' 后表示  '/' 后面的一个字符不作为通配符

同理 %做为通配符通配多个,但使用 ESCAPE '/' 后即为寻常的字符不作为通配符使用

4. 使用mybatis like 特殊字符 '$' 报错问题

如果我向mybatis 中like后面获取的字段中传一个 $ 符,结果就报错了,错误如下

### Cause: java.lang.IllegalArgumentException: Illegal group reference
at com.jd.dlink.service.core.BrandUserService.findByBrandNameAndGrade(BrandUserService.java:203)
at com.jd.dlink.service.core.BrandUserService$$FastClassBySpringCGLIB$$e2e2d142.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.jd.dlink.service.core.BrandUserService$$EnhancerBySpringCGLIB$$27ed270f.findByBrandNameAndGrade(<generated>)
at com.jd.dlink.market.controller.core.BrandUserController.findByBrandNameAndGrade(BrandUserController.java:307)
at com.jd.dlink.market.controller.core.BrandUserController$$FastClassBySpringCGLIB$$efe8cd76.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
at com.jd.ump.annotation.JAnnotation.execJAnnotation(JAnnotation.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.jd.dlink.market.controller.core.BrandUserController$$EnhancerBySpringCGLIB$$8ed5e318.findByBrandNameAndGrade(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1496)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1484)
at com.jd.dlink.common.accesslog.AccessFilter.doFilter(AccessFilter.java:65)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1484)
at com.jd.dlink.common.xss.StripXssFilter.doFilter(StripXssFilter.java:21)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1476)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:667)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Unknown Source)

费了九牛二虎之力,终于发现是mybatis拼接字符串的问题,

原来的mybatis sql 是这样的:

SELECT name FROM table
<where>
  <if test="name != null">
    AND name LIKE '%#{name}%' ESCAPE '/'
  </if>
</where>

修改后的sql如下:

SELECT name FROM table
<where>
  <if test="name != null">
    AND name LIKE '%${name}%'  ESCAPE '/'
  </if> 
</where>

这样就不会报错啦~~~