private static String getCountSql(String sql) {
return "select count(*) from "+cutOrderByOrGroupBy(getFromHql(sql));
} private static String cutOrderByOrGroupBy(String hql) {
int lastFromIndex = hql.lastIndexOf(" from ");
int lastOG = hql.lastIndexOf(" order by ");
if (lastOG < 0) {
lastOG = hql.lastIndexOf(" group by ");
}
if (lastFromIndex < lastOG) {
return hql.substring(0, lastOG);
}
return hql;
} private static String getFromHql(String sql) {
String tmpSql = sql;
int fIndex = tmpSql.indexOf(" from ");
tmpSql = tmpSql.substring(fIndex+5);
//确保from没被( 和 )包裹起来,即为该语句主from
if (!equalOpenAndCloseParenthesis(tmpSql)) {
tmpSql = getFromHql(tmpSql);
}
return tmpSql;
} private static Boolean equalOpenAndCloseParenthesis(String subSql) {
final Pattern opPattern = Pattern.compile("\\(");
final Matcher opMatch = opPattern.matcher(subSql);
final List<String> opMatches = new ArrayList<String>();
while (opMatch.find()) {
opMatches.add(opMatch.group(0));
}
final Pattern cpPattern = Pattern.compile("\\)");
final Matcher cpMatch = cpPattern.matcher(subSql);
final List<String> cpMatches = new ArrayList<String>();
while (cpMatch.find()) {
cpMatches.add(cpMatch.group(0));
}
return opMatches.size() == cpMatches.size();
}
根据from左右两侧括号情况判断某个from是否是主sql的from关键字。