Java tutorial
/* The MIT License (MIT) Copyright (c) 2014 abel533@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.pagehelper; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.beanutils.PropertyUtils; import org.apache.ibatis.binding.MapperMethod; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.ResultMap; import org.apache.ibatis.mapping.ResultMapping; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.Interceptor; 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.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.factory.ObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import com.foundationdb.sql.StandardException; import com.foundationdb.sql.parser.FromBaseTable; import com.foundationdb.sql.parser.OrderByList; import com.foundationdb.sql.parser.SQLParser; import com.foundationdb.sql.parser.StatementNode; import com.foundationdb.sql.unparser.NodeToString; /** * Mybatis - * * @author liuzh/abel533/isea533 * @version 3.3.0 * ? : http://git.oschina.net/free/Mybatis_PageHelper */ @Intercepts(@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class })) public class PageHelper implements Interceptor { public static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory(); public static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory(); /** * ??Mybatis? * * @param object ?? * @return */ public static MetaObject forObject(Object object) { return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY); } /** * ? - order by ? */ private static class UnParser extends NodeToString { private static final SQLParser PARSER = new SQLParser(); public String removeOrderBy(String sql) throws StandardException { StatementNode stmt = PARSER.parseStatement(sql); String result = toString(stmt); if (result.indexOf('$') > -1) { result = result.replaceAll("\\$\\d+", "?"); } return result; } @Override protected String orderByList(OrderByList node) throws StandardException { //order by?? // order by${param}? // ??order by??? String sql = nodeList(node); if (sql.indexOf('$') > -1) { return sql; } return ""; } @Override protected String fromBaseTable(FromBaseTable node) throws StandardException { String tn = toString(node.getOrigTableName()); String n = node.getCorrelationName(); if (n == null) { return tn; } else if (dialect.equals("oracle")) { //Oracle??AS return tn + " " + n; } else { return tn + " AS " + n; } } } //SQL??? private static final UnParser UNPARSER = new UnParser(); //id? private static final String SUFFIX_PAGE = "_PageHelper"; //countid? private static final String SUFFIX_COUNT = SUFFIX_PAGE + "_Count"; //? private static final String PAGEPARAMETER_FIRST = "First" + SUFFIX_PAGE; //? private static final String PAGEPARAMETER_SECOND = "Second" + SUFFIX_PAGE; private static final String BOUND_SQL = "boundSql.sql"; private static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>(); private static final List<ResultMapping> EMPTY_RESULTMAPPING = new ArrayList<ResultMapping>(0); //? private static String dialect = ""; //RowBounds?offsetPageNum - ? private static boolean offsetAsPageNum = false; //RowBounds?count - ? private static boolean rowBoundsWithCount = false; //truepagesize0RowBoundslimit=0? private static boolean pageSizeZero = false; /** * * * @param pageNo ? * @param pageSize ?? */ public static void startPage(int pageNo, int pageSize) { startPage(pageNo, pageSize, true); } /** * * * @param pageNum ? * @param pageSize ?? * @param count ?count */ public static void startPage(int pageNum, int pageSize, boolean count) { LOCAL_PAGE.set(new Page(pageNum, pageSize, count)); } /** * ?? * * @param rowBounds RowBounds? * @return Page */ private Page getPage(RowBounds rowBounds) { Page page = LOCAL_PAGE.get(); //?? LOCAL_PAGE.remove(); if (page == null) { if (offsetAsPageNum) { page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount); } else { page = new Page(rowBounds, rowBoundsWithCount); } } return page; } /** * Mybatis * * @param invocation ? * @return * @throws Throwable */ @Override public Object intercept(Invocation invocation) throws Throwable { final Object[] args = invocation.getArgs(); RowBounds rowBounds = (RowBounds) args[2]; if (LOCAL_PAGE.get() == null && rowBounds == RowBounds.DEFAULT) { return invocation.proceed(); } else { //RowBounds-?Mybatis args[2] = RowBounds.DEFAULT; MappedStatement ms = (MappedStatement) args[0]; Object parameterObject = args[1]; //? Page page = getPage(rowBounds); //pageSizeZero if (pageSizeZero && page.getPageSize() == 0) { //? Object result = invocation.proceed(); //? page.addAll((List) result); // // page.setPageNum(1); page.setPageNo(1); //?pageSize=total page.setPageSize(page.size()); //??total page.setTotalNum(page.size()); //?Page - ??? return page; } //?total??count if (page.isCount()) { BoundSql boundSql = ms.getBoundSql(parameterObject); //?MappedStatement?qs args[0] = getMappedStatement(ms, boundSql, SUFFIX_COUNT); // Object result = invocation.proceed(); // page.setTotalNum((Integer) ((List) result).get(0)); if (page.getTotalNum() == 0) { return page; } } //pageSize>0pageSize<=0???count if (page.getPageSize() > 0) { BoundSql boundSql = ms.getBoundSql(parameterObject); //?MappedStatement?qs args[0] = getMappedStatement(ms, boundSql, SUFFIX_PAGE); //parameterObject? args[1] = setPageParameter(parameterObject, boundSql, page); // Object result = invocation.proceed(); //? page.addAll((List) result); } // return page; } } /** * ?sql - ???? * * @param sql sql * @return countsql */ private String getCountSql(final String sql) { try { if (sql.toUpperCase().contains(" ORDER ")) { return "select count(0) from (" + UNPARSER.removeOrderBy(sql) + ") tmp_count"; } } catch (Exception e) { //ignore e.printStackTrace(); } return "select count(0) from (" + sql + ") tmp_count"; } /** * ?sql - ???? * * @param sql sql * @return sql */ private String getPageSql(String sql) { StringBuilder pageSql = new StringBuilder(200); if ("mysql".equals(dialect)) { pageSql.append("select * from ("); pageSql.append(sql); pageSql.append(") as tmp_page limit ?,?"); } else if ("hsqldb".equals(dialect)) { pageSql.append(sql); pageSql.append(" LIMIT ? OFFSET ?"); } else if ("oracle".equals(dialect)) { pageSql.append("select * from ( select temp.*, rownum row_id from ( "); pageSql.append(sql); pageSql.append(" ) temp where rownum <= ? ) where row_id > ?"); } return pageSql.toString(); } /** * ??? * * @param parameterObject ? * @param page ? * @return ?? * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ private MapperMethod.ParamMap setPageParameter(Object parameterObject, BoundSql boundSql, Page page) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { MapperMethod.ParamMap<Object> paramMap = null; if (parameterObject == null) { paramMap = new MapperMethod.ParamMap<Object>(); } else if (parameterObject instanceof MapperMethod.ParamMap) { paramMap = (MapperMethod.ParamMap) parameterObject; } else { paramMap = new MapperMethod.ParamMap<Object>(); if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) { for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) { if (!parameterMapping.getProperty().equals(PAGEPARAMETER_FIRST) && !parameterMapping.getProperty().equals(PAGEPARAMETER_SECOND)) { if (parameterObject instanceof Map) { paramMap.put(parameterMapping.getProperty(), ((Map) parameterObject).get(parameterMapping.getProperty())); } else { // paramMap.put(parameterMapping.getProperty(), parameterObject); Object value = PropertyUtils.getSimpleProperty(parameterObject, parameterMapping.getProperty()); System.out.println("set param: ??: " + parameterMapping.getProperty() + " , value: " + value); paramMap.put(parameterMapping.getProperty(), value); } // System.out.println("parameterObject: "+parameterObject.getClass()); // paramMap.put(parameterMapping.getProperty(), 86); } } } } if ("mysql".equals(dialect)) { paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize()); } else if ("hsqldb".equals(dialect)) { paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); } else if ("oracle".equals(dialect)) { paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); } return paramMap; } /** * ?ms - ms??? * * @param ms * @param boundSql * @param suffix * @return */ private MappedStatement getMappedStatement(MappedStatement ms, BoundSql boundSql, String suffix) { MappedStatement qs = null; try { qs = ms.getConfiguration().getMappedStatement(ms.getId() + suffix); } catch (Exception e) { //ignore } if (qs == null) { //MappedStatement qs = newMappedStatement(ms, new BoundSqlSqlSource(boundSql), suffix); try { ms.getConfiguration().addMappedStatement(qs); } catch (Exception e) { //ignore } } return qs; } private class BoundSqlSqlSource implements SqlSource { BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) { this.boundSql = boundSql; } public BoundSql getBoundSql(Object parameterObject) { return boundSql; } public BoundSql getBoundSql() { return boundSql; } } /** * countMappedStatement * * @param ms * @param newSqlSource * @param suffix * @return */ private MappedStatement newMappedStatement(MappedStatement ms, BoundSqlSqlSource newSqlSource, String suffix) { String id = ms.getId() + suffix; //? if (suffix == SUFFIX_PAGE) { //sql MetaObject msObject = forObject(newSqlSource); msObject.setValue(BOUND_SQL, getPageSql((String) msObject.getValue(BOUND_SQL))); //? List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(); newParameterMappings.addAll(newSqlSource.getBoundSql().getParameterMappings()); newParameterMappings .add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class) .build()); newParameterMappings .add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class) .build()); msObject.setValue("boundSql.parameterMappings", newParameterMappings); } else { //count sql MetaObject msObject = forObject(newSqlSource); msObject.setValue(BOUND_SQL, getCountSql((String) msObject.getValue(BOUND_SQL))); } MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), id, newSqlSource, ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) { StringBuilder keyProperties = new StringBuilder(); for (String keyProperty : ms.getKeyProperties()) { keyProperties.append(keyProperty).append(","); } keyProperties.delete(keyProperties.length() - 1, keyProperties.length()); builder.keyProperty(keyProperties.toString()); } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); if (suffix == SUFFIX_PAGE) { builder.resultMaps(ms.getResultMaps()); } else { //countint List<ResultMap> resultMaps = new ArrayList<ResultMap>(); ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), id, int.class, EMPTY_RESULTMAPPING) .build(); resultMaps.add(resultMap); builder.resultMaps(resultMaps); } builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); return builder.build(); } /** * ?Executor * * @param target * @return */ @Override public Object plugin(Object target) { if (target instanceof Executor) { return Plugin.wrap(target, this); } else { return target; } } /** * * * @param p */ public void setProperties(Properties p) { dialect = p.getProperty("dialect"); if (dialect == null || "".equals(dialect)) { throw new RuntimeException("Mybatis?PageHelper?dialect?!"); } //offsetPageNum String offset = p.getProperty("offsetAsPageNum"); if (offset != null && "TRUE".equalsIgnoreCase(offset)) { offsetAsPageNum = true; } //RowBounds???count String withcount = p.getProperty("rowBoundsWithCount"); if (withcount != null && "TRUE".equalsIgnoreCase(withcount)) { rowBoundsWithCount = true; } //truepagesize0RowBoundslimit=0? String sizeZero = p.getProperty("pageSizeZero"); if (sizeZero != null && "TRUE".equalsIgnoreCase(sizeZero)) { pageSizeZero = true; } } }