上传代码

This commit is contained in:
zhangdongxu
2017-12-19 14:55:52 +08:00
commit 13acafd43d
4777 changed files with 898870 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* Cluster方言的实现[神通数据库]
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class ClusterDialect implements Dialect {
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset),
Integer.toString(limit));
}
public boolean supportsLimit() {
return true;
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
StringBuilder stringBuilder = new StringBuilder(sql);
if(stringBuilder.indexOf("limit") == -1 && stringBuilder.indexOf("LIMIT") == -1 ){
stringBuilder.append(" limit ");
stringBuilder.append(limitPlaceholder);
stringBuilder.append(" offset ");
stringBuilder.append(offsetPlaceholder);
}
System.out.println("cluster分页sql"+stringBuilder.toString());
return stringBuilder.toString();
}
}

View File

@@ -0,0 +1,88 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* DB2的分页数据库方言实现
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class DB2Dialect implements Dialect {
@Override
public boolean supportsLimit() {
return true;
}
private static String getRowNumber(String sql) {
StringBuilder rownumber = new StringBuilder(50)
.append("rownumber() over(");
int orderByIndex = sql.toLowerCase().indexOf("order by");
if (orderByIndex > 0 && !hasDistinct(sql)) {
rownumber.append(sql.substring(orderByIndex));
}
rownumber.append(") as rownumber_,");
return rownumber.toString();
}
private static boolean hasDistinct(String sql) {
return sql.toLowerCase().contains("select distinct");
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
int startOfSelect = sql.toLowerCase().indexOf("select");
StringBuilder pagingSelect = new StringBuilder(sql.length() + 100)
.append(sql.substring(0, startOfSelect)) //add the comment
.append("select * from ( select ") //nest the main query in an outer select
.append(getRowNumber(sql)); //add the rownnumber bit into the outer query select list
if (hasDistinct(sql)) {
pagingSelect.append(" row_.* from ( ") //add another (inner) nested select
.append(sql.substring(startOfSelect)) //add the main query
.append(" ) as row_"); //close off the inner nested select
} else {
pagingSelect.append(sql.substring(startOfSelect + 6)); //add the main query
}
pagingSelect.append(" ) as temp_ where rownumber_ ");
//add the restriction to the outer select
if (offset > 0) {
// int end = offset + limit;
String endString = offsetPlaceholder + "+" + limitPlaceholder;
pagingSelect.append("between ").append(offsetPlaceholder)
.append("+1 and ").append(endString);
} else {
pagingSelect.append("<= ").append(limitPlaceholder);
}
return pagingSelect.toString();
}
}

View File

@@ -0,0 +1,43 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class DerbyDialect implements Dialect {
@Override
public boolean supportsLimit() {
return false;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
// return getLimitString(sql,offset,Integer.toString(offset),limit,Integer.toString(limit));
throw new UnsupportedOperationException("paged queries not supported");
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limit 分页每页显示纪录条数
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset,String offsetPlaceholder, int limit, String limitPlaceholder) {
throw new UnsupportedOperationException( "paged queries not supported" );
}
}

View File

@@ -0,0 +1,33 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* 类似hibernate的Dialect,但只精简出分页部分
*
* @author poplar.yfyang
* @version 1.0 2011-11-18 下午12:31
* @since JDK 1.5
*/
public interface Dialect {
/**
* 数据库本身是否支持分页当前的分页查询方式
* 如果数据库不支持的话,则不进行数据库分页
*
* @return true支持当前的分页查询方式
*/
public boolean supportsLimit();
/**
* 将sql转换为分页SQL分别调用分页sql
*
* @param sql SQL语句
* @param offset 开始条数
* @param limit 每页显示多少纪录条数
* @return 分页查询的sql
*/
public String getLimitString(String sql, int offset, int limit);
}

View File

@@ -0,0 +1,44 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* A dialect compatible with the H2 database.
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class H2Dialect implements Dialect {
public boolean supportsLimit() {
return true;
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limit 分页每页显示纪录条数
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
private String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
return sql + ((offset > 0) ? " limit " + limitPlaceholder + " offset "
+ offsetPlaceholder : " limit " + limitPlaceholder);
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset), limit, Integer.toString(limit));
}
}

View File

@@ -0,0 +1,49 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* Dialect for HSQLDB
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class HSQLDialect implements Dialect {
@Override
public boolean supportsLimit() {
return true;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset),
Integer.toString(limit));
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
boolean hasOffset = offset > 0;
return
new StringBuffer(sql.length() + 10)
.append(sql)
.insert(sql.toLowerCase().indexOf("select") + 6, hasOffset ? " limit " + offsetPlaceholder + " " + limitPlaceholder : " top " + limitPlaceholder)
.toString();
}
}

View File

@@ -0,0 +1,52 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* Mysql方言的实现
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class MySQLDialect implements Dialect {
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset),
Integer.toString(limit));
}
public boolean supportsLimit() {
return true;
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
StringBuilder stringBuilder = new StringBuilder(sql);
stringBuilder.append(" limit ");
if (offset > 0) {
stringBuilder.append(offsetPlaceholder).append(",").append(limitPlaceholder);
} else {
stringBuilder.append(limitPlaceholder);
}
return stringBuilder.toString();
}
}

View File

@@ -0,0 +1,67 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* Oracle的方言实现
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class OracleDialect implements Dialect {
@Override
public boolean supportsLimit() {
return true;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
sql = sql.trim();
boolean isForUpdate = false;
if (sql.toLowerCase().endsWith(" for update")) {
sql = sql.substring(0, sql.length() - 11);
isForUpdate = true;
}
StringBuilder pagingSelect = new StringBuilder(sql.length() + 100);
if (offset > 0) {
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
} else {
pagingSelect.append("select * from ( ");
}
pagingSelect.append(sql);
if (offset > 0) {
String endString = offsetPlaceholder + "+" + limitPlaceholder;
pagingSelect.append(" ) row_ where rownum <= "+endString+") where rownum_ > ").append(offsetPlaceholder);
} else {
pagingSelect.append(" ) where rownum <= "+limitPlaceholder);
}
if (isForUpdate) {
pagingSelect.append(" for update");
}
return pagingSelect.toString();
}
}

View File

@@ -0,0 +1,47 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* Postgre Sql的方言实现
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class PostgreSQLDialect implements Dialect {
public boolean supportsLimit() {
return true;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset),
Integer.toString(limit));
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset,
String offsetPlaceholder, String limitPlaceholder) {
StringBuilder pageSql = new StringBuilder().append(sql);
pageSql = offset <= 0
? pageSql.append(" limit ").append(limitPlaceholder) :
pageSql.append(" limit ").append(limitPlaceholder).append(" offset ").append(offsetPlaceholder);
return pageSql.toString();
}
}

View File

@@ -0,0 +1,94 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
import org.apache.commons.lang3.StringUtils;
/**
* Sql 2005的方言实现
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class SQLServer2005Dialect implements Dialect {
@Override
public boolean supportsLimit() {
return true;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset,
limit, Integer.toString(limit));
}
/**
* Add a LIMIT clause to the given SQL SELECT
* <p/>
* The LIMIT SQL will look like:
* <p/>
* WITH query AS
* (SELECT TOP 100 percent ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __row_number__, * from table_name)
* SELECT *
* FROM query
* WHERE __row_number__ BETWEEN :offset and :lastRows
* ORDER BY __row_number__
*
* @param querySqlString The SQL statement to base the limit query off of.
* @param offset Offset of the first row to be returned by the query (zero-based)
* @param limit Maximum number of rows to be returned by the query
* @param limitPlaceholder limitPlaceholder
* @return A new SQL statement with the LIMIT clause applied.
*/
private String getLimitString(String querySqlString, int offset, int limit, String limitPlaceholder) {
StringBuilder pagingBuilder = new StringBuilder();
String orderby = getOrderByPart(querySqlString);
String distinctStr = "";
String loweredString = querySqlString.toLowerCase();
String sqlPartString = querySqlString;
if (loweredString.trim().startsWith("select")) {
int index = 6;
if (loweredString.startsWith("select distinct")) {
distinctStr = "DISTINCT ";
index = 15;
}
sqlPartString = sqlPartString.substring(index);
}
pagingBuilder.append(sqlPartString);
// if no ORDER BY is specified use fake ORDER BY field to avoid errors
if (StringUtils.isEmpty(orderby)) {
orderby = "ORDER BY CURRENT_TIMESTAMP";
}
StringBuilder result = new StringBuilder();
result.append("WITH query AS (SELECT ")
.append(distinctStr)
.append("TOP 100 PERCENT ")
.append(" ROW_NUMBER() OVER (")
.append(orderby)
.append(") as __row_number__, ")
.append(pagingBuilder)
.append(") SELECT * FROM query WHERE __row_number__ BETWEEN ")
.append(offset).append(" AND ").append(offset + limit)
.append(" ORDER BY __row_number__");
return result.toString();
}
static String getOrderByPart(String sql) {
String loweredString = sql.toLowerCase();
int orderByIndex = loweredString.indexOf("order by");
if (orderByIndex != -1) {
// if we find a new "order by" then we need to ignore
// the previous one since it was probably used for a subquery
return sql.substring(orderByIndex);
} else {
return "";
}
}
}

View File

@@ -0,0 +1,54 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* MSSQLServer 数据库实现分页方言
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class SQLServerDialect implements Dialect {
public boolean supportsLimit() {
return true;
}
static int getAfterSelectInsertPoint(String sql) {
int selectIndex = sql.toLowerCase().indexOf("select");
final int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
}
public String getLimitString(String sql, int offset, int limit) {
return getLimit(sql, offset, limit);
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param limit 分页每页显示纪录条数
* @return 包含占位符的分页sql
*/
public String getLimit(String sql, int offset, int limit) {
if (offset > 0) {
throw new UnsupportedOperationException("sql server has no offset");
}
return new StringBuffer(sql.length() + 8)
.append(sql)
.insert(getAfterSelectInsertPoint(sql), " top " + limit)
.toString();
}
}

View File

@@ -0,0 +1,46 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.dialect;
/**
* Sybase数据库分页方言实现。
* 还未实现
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class SybaseDialect implements Dialect {
public boolean supportsLimit() {
return false;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return null;
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limit 分页每页显示纪录条数
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
throw new UnsupportedOperationException("paged queries not supported");
}
}

View File

@@ -0,0 +1,59 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.interceptor;
import java.io.Serializable;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.plugin.Interceptor;
import com.nis.domain.Page;
import com.nis.util.Reflections;
/**
* Mybatis分页拦截器基类
* @author poplar.yfyang / thinkgem
* @version 2013-8-28
*/
public abstract class BaseInterceptor implements Interceptor, Serializable {
private static final long serialVersionUID = 1L;
protected static final String PAGE = "page";
protected static final String DELEGATE = "delegate";
protected static final String MAPPED_STATEMENT = "mappedStatement";
protected Log log = LogFactory.getLog(this.getClass());
// /**
// * 拦截的ID在mapper中的id可以匹配正则
// */
// protected String _SQL_PATTERN = "";
/**
* 对参数进行转换和检查
* @param parameterObject 参数对象
* @param page 分页对象
* @return 分页对象
* @throws NoSuchFieldException 无法找到参数
*/
@SuppressWarnings("unchecked")
protected static Page<Object> convertParameter(Object parameterObject, Page<Object> page) {
try{
if (parameterObject instanceof Page) {
return (Page<Object>) parameterObject;
} else {
return (Page<Object>)Reflections.getFieldValue(parameterObject, PAGE);
}
}catch (Exception e) {
return null;
}
}
}

View File

@@ -0,0 +1,130 @@
package com.nis.persistence.interceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import com.nis.domain.Page;
import com.nis.util.Reflections;
import com.nis.util.StringUtils;
import java.util.Properties;
/**
* 数据库分页插件,只拦截查询语句.
* @author poplar.yfyang / thinkgem
* @version 2013-8-28
*/
@Intercepts({@Signature(type = Executor.class, method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class PaginationInterceptor extends BaseInterceptor {
private static final long serialVersionUID = 1L;
@Override
public Object intercept(Invocation invocation) throws Throwable {
final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// //拦截需要分页的SQL
//// if (mappedStatement.getId().matches(_SQL_PATTERN)) {
// if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) {
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Object parameterObject = boundSql.getParameterObject();
//获取分页参数对象
Page<Object> page = null;
if (parameterObject != null) {
page = convertParameter(parameterObject, page);
}
//如果设置了分页对象,则进行分页
if (page != null && page.getPageSize() != -1) {
if (StringUtils.isBlank(boundSql.getSql())){
return null;
}
String originalSql = boundSql.getSql().trim();
//得到总记录数
if(page.getCount() == -1l){
page.setCount(0);
}else{
page.setCount(SQLHelper.getCount(originalSql, null, mappedStatement, parameterObject, boundSql, log));
}
//分页查询 本地化对象 修改数据库注意修改实现
String pageSql = SQLHelper.generatePageSql(originalSql, page);
// if (log.isDebugEnabled()) {
// log.debug("PAGE SQL:" + StringUtils.replace(pageSql, "\n", ""));
// }
invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
//解决MyBatis 分页foreach 参数失效 start
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) {
MetaObject mo = (MetaObject) Reflections.getFieldValue(boundSql, "metaParameters");
Reflections.setFieldValue(newBoundSql, "metaParameters", mo);
}
//解决MyBatis 分页foreach 参数失效 end
MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
invocation.getArgs()[0] = newMs;
}
// }
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
private MappedStatement copyFromMappedStatement(MappedStatement ms,
SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(),
ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null) {
for (String keyProperty : ms.getKeyProperties()) {
builder.keyProperty(keyProperty);
}
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.cache(ms.getCache());
return builder.build();
}
public static class BoundSqlSqlSource implements SqlSource {
BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
@Override
public void setProperties(Properties properties) {
}
}

View File

@@ -0,0 +1,88 @@
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.nis.persistence.interceptor;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import com.nis.domain.Page;
import com.nis.util.Reflections;
import java.sql.Connection;
import java.util.Properties;
/**
* Mybatis数据库分页插件拦截StatementHandler的prepare方法
* @author poplar.yfyang / thinkgem
* @version 2013-8-28
*/
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})
})
public class PreparePaginationInterceptor extends BaseInterceptor {
private static final long serialVersionUID = 1L;
public PreparePaginationInterceptor() {
super();
}
@Override
public Object intercept(Invocation ivk) throws Throwable {
if (ivk.getTarget().getClass().isAssignableFrom(RoutingStatementHandler.class)) {
final RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();
final BaseStatementHandler delegate = (BaseStatementHandler) Reflections.getFieldValue(statementHandler, DELEGATE);
final MappedStatement mappedStatement = (MappedStatement) Reflections.getFieldValue(delegate, MAPPED_STATEMENT);
// //拦截需要分页的SQL
//// if (mappedStatement.getId().matches(_SQL_PATTERN)) {
// if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) {
BoundSql boundSql = delegate.getBoundSql();
//分页SQL<select>中parameterType属性对应的实体参数即Mapper接口中执行分页方法的参数,该参数不得为空
Object parameterObject = boundSql.getParameterObject();
if (parameterObject == null) {
log.error("参数未实例化");
throw new NullPointerException("parameterObject尚未实例化");
} else {
final Connection connection = (Connection) ivk.getArgs()[0];
final String sql = boundSql.getSql();
//记录统计
final Long count = SQLHelper.getCount(sql, connection, mappedStatement, parameterObject, boundSql, log);
Page<Object> page = null;
page = convertParameter(parameterObject, page);
page.setCount(count);
String pagingSql = SQLHelper.generatePageSql(sql, page);
if (log.isDebugEnabled()) {
log.debug("PAGE SQL:" + pagingSql);
}
//将分页sql语句反射回BoundSql.
Reflections.setFieldValue(boundSql, "sql", pagingSql);
}
if (boundSql.getSql() == null || "".equals(boundSql.getSql())){
return null;
}
}
// }
return ivk.proceed();
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
}

View File

@@ -0,0 +1,308 @@
package com.nis.persistence.interceptor;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.log4j.Logger;
import com.nis.datasource.CustomerContextHolder;
import com.nis.domain.Page;
import com.nis.persistence.dialect.ClusterDialect;
import com.nis.persistence.dialect.DB2Dialect;
import com.nis.persistence.dialect.DerbyDialect;
import com.nis.persistence.dialect.Dialect;
import com.nis.persistence.dialect.H2Dialect;
import com.nis.persistence.dialect.HSQLDialect;
import com.nis.persistence.dialect.MySQLDialect;
import com.nis.persistence.dialect.OracleDialect;
import com.nis.persistence.dialect.PostgreSQLDialect;
import com.nis.persistence.dialect.SQLServer2005Dialect;
import com.nis.persistence.dialect.SybaseDialect;
import com.nis.util.Configurations;
import com.nis.util.Reflections;
import com.nis.util.StringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* SQL工具类
*
* @author poplar.yfyang / thinkgem
* @version 2013-8-28
*/
public class SQLHelper {
static final Logger logger = Logger.getLogger(SQLHelper.class);
/**
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
*
* @param ps
* 表示预编译的 SQL 语句的对象。
* @param mappedStatement
* MappedStatement
* @param boundSql
* SQL
* @param parameterObject
* 参数对象
* @throws java.sql.SQLException
* 数据库异常
*/
@SuppressWarnings("unchecked")
public static void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,
Object parameterObject) throws SQLException {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
Configuration configuration = mappedStatement.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
PropertyTokenizer prop = new PropertyTokenizer(propertyName);
if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)
&& boundSql.hasAdditionalParameter(prop.getName())) {
value = boundSql.getAdditionalParameter(prop.getName());
if (value != null) {
value = configuration.newMetaObject(value)
.getValue(propertyName.substring(prop.getName().length()));
}
} else {
value = metaObject == null ? null : metaObject.getValue(propertyName);
}
@SuppressWarnings("rawtypes")
TypeHandler typeHandler = parameterMapping.getTypeHandler();
if (typeHandler == null) {
throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName
+ " of statement " + mappedStatement.getId());
}
typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
}
}
}
}
/**
*
* @Title: getDBType
* @Description: TODO(根据动态数据塬获取数据库的类型)
* @param @return
* 入参
* @return String 返回类型
* @author darnell
* @throws @date
* 2016年8月15日 下午6:35:58
* @version V1.0
*/
public static String getDBType() {
String dataSource = CustomerContextHolder.getCustomerType();
if (StringUtils.isBlank(dataSource)) {
return "mysql";
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_A)) {
return "mysql";
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_B)) {
return "oracle";
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_C)) {
return "oracle";
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_D)) {
return "oracle";
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_F)) {
return "oracle";
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_G)) {
return "oracle";
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_H)) {//神通数据库
return "cluster";
}else {
return "mysql";
}
}
/**
* 查询总纪录数
*
* @param sql
* SQL语句
* @param connection
* 数据库连接
* @param mappedStatement
* mapped
* @param parameterObject
* 参数
* @param boundSql
* boundSql
* @return 总记录数
* @throws SQLException
* sql查询错误
*/
public static Long getCount(final String sql, final Connection connection, final MappedStatement mappedStatement,
final Object parameterObject, final BoundSql boundSql, Log log) throws SQLException {
logger.info("oracle查询count开始----"+System.currentTimeMillis());
String dbName = getDBType();
final String countSql;
if ("oracle".equals(dbName)) {
countSql = "select count(*) from (" + removeOrders(sql) + ") tmp_count";
} else {
if(sql.toLowerCase().indexOf("limit") >-1){
countSql = "select count(*) from (" +sql+ ") tmp_count";
}else{
countSql = "select count(*) from (" + removeOrders(sql) + ") tmp_count";
}
}
System.out.println("countSql:"+countSql);
Connection conn = connection;
PreparedStatement ps = null;
ResultSet rs = null;
try {
if (log.isDebugEnabled()) {
log.debug("COUNT SQL: "
+ StringUtils.replaceEach(countSql, new String[] { "\n", "\t" }, new String[] { " ", " " }));
}
if (conn == null) {
conn = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection();
}
ps = conn.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,
boundSql.getParameterMappings(), parameterObject);
// 解决MyBatis 分页foreach 参数失效 start
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) {
MetaObject mo = (MetaObject) Reflections.getFieldValue(boundSql, "metaParameters");
Reflections.setFieldValue(countBS, "metaParameters", mo);
}
// 解决MyBatis 分页foreach 参数失效 end
SQLHelper.setParameters(ps, mappedStatement, countBS, parameterObject);
rs = ps.executeQuery();
Long count = 0l;
if (rs.next()) {
count = rs.getLong(1);
}
return count;
} finally {
logger.info("oracle查询count结束----"+System.currentTimeMillis());
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
/**
* 根据数据库方言生成特定的分页sql
*
* @param sql
* Mapper中的Sql语句
* @param page
* 分页对象
* @param dialect
* 方言类型
* @return 分页SQL
*/
public static String generatePageSql(String sql, Page<Object> page) {
Dialect dialect = getDBDialect();
if (dialect.supportsLimit()) {
return dialect.getLimitString(sql, page.getFirstResult(), page.getMaxResults());
} else {
return sql;
}
}
/**
* 设置属性,支持自定义方言类和制定数据库的方式 <code>dialectClass</code>,自定义方言类。可以不配置这项
* <ode>dbms</ode> 数据库类型,插件支持的数据库 <code>sqlPattern</code> 需要拦截的SQL ID
*
* @param p
* 属性
*/
public static Dialect getDBDialect() {
Dialect dialect = null;
String dbType = getDBType();
if ("db2".equals(dbType)) {
dialect = new DB2Dialect();
} else if ("derby".equals(dbType)) {
dialect = new DerbyDialect();
} else if ("h2".equals(dbType)) {
dialect = new H2Dialect();
} else if ("hsql".equals(dbType)) {
dialect = new HSQLDialect();
} else if ("mysql".equals(dbType)) {
dialect = new MySQLDialect();
} else if ("oracle".equals(dbType)) {
dialect = new OracleDialect();
} else if ("postgre".equals(dbType)) {
dialect = new PostgreSQLDialect();
} else if ("mssql".equals(dbType) || "sqlserver".equals(dbType)) {
dialect = new SQLServer2005Dialect();
} else if ("sybase".equals(dbType)) {
dialect = new SybaseDialect();
}else if ("cluster".equals(dbType)) {
dialect = new ClusterDialect();
}
if (dialect == null) {
throw new RuntimeException("mybatis dialect error.");
}
return dialect;
}
/**
* 去除qlString的select子句。
*
* @param hql
* @return
*/
@SuppressWarnings("unused")
private static String removeSelect(String qlString) {
int beginPos = qlString.toLowerCase().indexOf("from");
return qlString.substring(beginPos);
}
/**
* 去除hql的orderBy子句。
*
* @param hql
* @return
*/
@SuppressWarnings("unused")
private static String removeOrders(String qlString) {
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(qlString);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "");
}
m.appendTail(sb);
return sb.toString();
}
}