MySql5PageHepler.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.edu.mybatis.dialect;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class MySql5PageHepler
  5. {
  6. private static int getAfterFormInsertPoint(String querySelect)
  7. {
  8. String regex = "\\s+FROM\\s+";
  9. Pattern pattern = Pattern.compile(regex, 2);
  10. Matcher matcher = pattern.matcher(querySelect);
  11. while (matcher.find()) {
  12. int fromStartIndex = matcher.start(0);
  13. String text = querySelect.substring(0, fromStartIndex);
  14. if (isBracketCanPartnership(text)) {
  15. return fromStartIndex;
  16. }
  17. }
  18. return 0;
  19. }
  20. public static String getCountString(String querySelect)
  21. {
  22. querySelect = getLineSql(querySelect);
  23. int orderIndex = getLastOrderInsertPoint(querySelect);
  24. int formIndex = getAfterFormInsertPoint(querySelect);
  25. String select = querySelect.substring(0, formIndex);
  26. if ((select.toLowerCase().indexOf("select distinct") != -1) || (querySelect.toLowerCase().indexOf("group by") != -1)) {
  27. return querySelect.length() + "select count(1) count from (" + querySelect.substring(0, orderIndex) + " ) t";
  28. }
  29. return querySelect.length() + "select count(1) count " + querySelect.substring(formIndex, orderIndex);
  30. }
  31. private static int getIndexOfCount(String text, char ch)
  32. {
  33. int count = 0;
  34. for (int i = 0; i < text.length(); i++) {
  35. count = text.charAt(i) == ch ? count + 1 : count;
  36. }
  37. return count;
  38. }
  39. private static int getLastOrderInsertPoint(String querySelect)
  40. {
  41. int orderIndex = querySelect.toLowerCase().lastIndexOf("order by");
  42. if ((orderIndex == -1) || (!isBracketCanPartnership(querySelect.substring(orderIndex, querySelect.length())))) {
  43. throw new RuntimeException("My SQL 分页必须要有Order by 语句!");
  44. }
  45. return orderIndex;
  46. }
  47. public static String getLimitString(String querySelect, int offset, int limit)
  48. {
  49. querySelect = getLineSql(querySelect);
  50. String sql = querySelect + " limit " + offset + " ," + limit;
  51. return sql;
  52. }
  53. private static String getLineSql(String sql)
  54. {
  55. return sql.replaceAll("[\r\n]", " ").replaceAll("\\s{2,}", " ");
  56. }
  57. private static boolean isBracketCanPartnership(String text)
  58. {
  59. return (text != null) && (getIndexOfCount(text, '(') == getIndexOfCount(text, ')'));
  60. }
  61. }