1 特殊字符转义—SQL模糊查询字段

  1. package com.orange.utils;
  2. import org.apache.commons.lang3.StringUtils;
  3. import java.util.Arrays;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.stream.Collectors;
  8. /**
  9. * 字符串工具类 用于模糊查询
  10. */
  11. public class StrUtil extends StringUtils {
  12. private static final Map<String,String> keyMap;
  13. /**
  14. * key --原字符
  15. * value -- 替换后字符
  16. */
  17. static {
  18. keyMap = new HashMap<>();
  19. keyMap.put("%","/%");
  20. keyMap.put("_","/_");
  21. keyMap.put("&","/&");
  22. keyMap.put("'","/'");
  23. keyMap.put(">","/%");
  24. keyMap.put("<","/%");
  25. keyMap.put("and","/");
  26. keyMap.put("or","/");
  27. }
  28. /**
  29. * 特俗字符转义--SQL模糊查询字段
  30. * @param keyWord
  31. * @return
  32. */
  33. public static String escapeExprSpecialWord(String keyWord){
  34. if(StringUtils.isBlank(keyWord)){
  35. return "";
  36. }
  37. /**
  38. * 特殊字符转义--SQL模糊查询字段
  39. */
  40. List<String> list = Arrays.asList(keyWord.split("")).stream()
  41. .map(mo -> {
  42. for (Map.Entry<String, String> fo : keyMap.entrySet()) {
  43. String key = fo.getKey();
  44. String value = fo.getValue();
  45. if (key.equals(mo)) {
  46. mo = mo.replace(key, value);
  47. }
  48. }
  49. return mo;
  50. }).collect(Collectors.toList());
  51. StringBuffer result = new StringBuffer();
  52. list.forEach(s -> result.append(s));
  53. return result.toString();
  54. }
  55. }