cn.yangjunda.hibernate_pagehelper.ErrorParser.SqlParser Maven / Gradle / Ivy
package cn.yangjunda.hibernate_pagehelper.ErrorParser;
/**
* Created by juanda on 12/6/17.
*/
public class SqlParser {
public SqlParser() {
}
private void isSupportedSql(String sql, String orderBy) {
if(sql.trim().toUpperCase().endsWith("FOR UPDATE")) {
throw new RuntimeException("分页插件不支持包含for update的sql");
}
if (sql ==null){
throw new RuntimeException("分页语句不能为空!");
}
if(orderBy!=null && sql.toLowerCase().lastIndexOf("top")>=0){
throw new RuntimeException("被分页的语句已经包含了Top,不能再通过分页插件进行分页查询!");
}
if(sql.toLowerCase().lastIndexOf("from")<0){
throw new RuntimeException("分页语句必须是包含from关键词的Select查询!");
}
}
public String getSimpleCountSql(String sql) {
this.isSupportedSql(sql,null);
StringBuilder stringBuilder = new StringBuilder(sql.length() + 40);
stringBuilder.append("select count(*) ");
stringBuilder.append(sql.substring(sql.toLowerCase().lastIndexOf("from")));
return stringBuilder.toString();
}
public String getPageSql(String sql,String orderBy) {
this.isSupportedSql(sql,orderBy);
StringBuilder stringBuilder = new StringBuilder(sql.length() + 40);
stringBuilder.append(sql);
if(orderBy!=null){
String[] orderByArray = orderBy.split(" ");
stringBuilder.append(" order by "+orderByArray[0]+" "+orderByArray[1]);
}
return stringBuilder.toString();
}
}