1 private static String getCountSql(String sql) { 2 return "select count(*) from "+cutOrderByOrGroupBy(getFromHql(sql)); 3 } 4 5 private static String cutOrderByOrGroupBy(String hql) { 6 int lastFromIndex = hql.lastIndexOf(" from "); 7 int lastOG = hql.lastIndexOf(" order by "); 8 if (lastOG < 0) { 9 lastOG = hql.lastIndexOf(" group by "); 10 } 11 if (lastFromIndex < lastOG) { 12 return hql.substring(0, lastOG); 13 } 14 return hql; 15 } 16 17 private static String getFromHql(String sql) { 18 String tmpSql = sql; 19 int fIndex = tmpSql.indexOf(" from "); 20 tmpSql = tmpSql.substring(fIndex+5); 21 //确保from没被( 和 )包裹起来,即为该语句主from 22 if (!equalOpenAndCloseParenthesis(tmpSql)) { 23 tmpSql = getFromHql(tmpSql); 24 } 25 return tmpSql; 26 } 27 28 private static Boolean equalOpenAndCloseParenthesis(String subSql) { 29 final Pattern opPattern = Pattern.compile("\("); 30 final Matcher opMatch = opPattern.matcher(subSql); 31 final List<String> opMatches = new ArrayList<String>(); 32 while (opMatch.find()) { 33 opMatches.add(opMatch.group(0)); 34 } 35 final Pattern cpPattern = Pattern.compile("\)"); 36 final Matcher cpMatch = cpPattern.matcher(subSql); 37 final List<String> cpMatches = new ArrayList<String>(); 38 while (cpMatch.find()) { 39 cpMatches.add(cpMatch.group(0)); 40 } 41 return opMatches.size() == cpMatches.size(); 42 }
根据from左右两侧括号情况判断某个from是否是主sql的from关键字。