();
- for (EntityHelper.EntityColumn column : entityColumns) {
- ParameterMapping.Builder builder = new ParameterMapping.Builder(ms.getConfiguration(), column.getProperty(), column.getJavaType());
- builder.mode(ParameterMode.IN);
- parameterMappings.add(builder.build());
- }
- return parameterMappings;
- }
-
- /**
- * 获取序列下个值的表达式
- *
- * @param column
- * @return
- */
- protected String getSeqNextVal(EntityHelper.EntityColumn column) {
- return MessageFormat.format(mapperHelper.getSeqFormat(), column.getSequenceName(), column.getColumn(), column.getProperty());
- }
-
- /**
- * 获取实体类的表名
- *
- * @param entityClass
- * @return
- */
- protected String tableName(Class> entityClass) {
- return mapperHelper.getTableName(entityClass);
- }
-
- /**
- * 返回if条件的sqlNode
- * 一般类型:<if test="property!=null">columnNode</if>
- *
- * @param column
- * @return
- */
- protected SqlNode getIfNotNull(EntityHelper.EntityColumn column, SqlNode columnNode) {
- return new IfSqlNode(columnNode, column.getProperty() + " != null ");
- }
-
- /**
- * 返回if条件的sqlNode
- * 一般类型:<if test="property==null">columnNode</if>
- *
- * @param column
- * @return
- */
- protected SqlNode getIfIsNull(EntityHelper.EntityColumn column, SqlNode columnNode) {
- return new IfSqlNode(columnNode, column.getProperty() + " == null ");
- }
-
- /**
- * 返回if条件的sqlNode
- * 一般类型:<if test="property!=null">columnNode</if>
- *
- * @param column
- * @return
- */
- protected SqlNode getIfCacheNotNull(EntityHelper.EntityColumn column, SqlNode columnNode) {
- return new IfSqlNode(columnNode, column.getProperty() + "_cache != null ");
- }
-
- /**
- * 返回if条件的sqlNode
- * 一般类型:<if test="property_cache!=null">columnNode</if>
- *
- * @param column
- * @return
- */
- protected SqlNode getIfCacheIsNull(EntityHelper.EntityColumn column, SqlNode columnNode) {
- return new IfSqlNode(columnNode, column.getProperty() + "_cache == null ");
- }
-
- /**
- * 获取 [AND] column = #{property}
- *
- * @param column
- * @param first
- * @return
- */
- protected SqlNode getColumnEqualsProperty(EntityHelper.EntityColumn column, boolean first) {
- return new StaticTextSqlNode((first ? "" : " AND ") + column.getColumn() + " = #{" + column.getProperty() + "} ");
- }
-
- /**
- * 获取所有列的where节点中的if判断列
- *
- * @param entityClass
- * @return
- */
- protected SqlNode getAllIfColumnNode(Class> entityClass) {
- //获取全部列
- List columnList = EntityHelper.getColumns(entityClass);
- List ifNodes = new ArrayList();
- boolean first = true;
- //对所有列循环,生成column = #{property}
- for (EntityHelper.EntityColumn column : columnList) {
- ifNodes.add(getIfNotNull(column, getColumnEqualsProperty(column, first)));
- first = false;
- }
- return new MixedSqlNode(ifNodes);
- }
-
- /**
- * 根据对象生成所有列的映射
- *
- * @param ms
- * @return
- */
- protected List getColumnParameterMappings(MappedStatement ms) {
- Class> entityClass = getSelectReturnType(ms);
- List entityColumns = EntityHelper.getColumns(entityClass);
- List parameterMappings = new ArrayList();
- for (EntityHelper.EntityColumn column : entityColumns) {
- ParameterMapping.Builder builder = new ParameterMapping.Builder(ms.getConfiguration(), column.getProperty(), column.getJavaType());
- builder.mode(ParameterMode.IN);
- parameterMappings.add(builder.build());
- }
- return parameterMappings;
- }
-
- /**
- * 新建SelectKey节点 - 只对mysql的自动增长有效,Oracle序列直接写到列中
- *
- * @param ms
- * @param column
- */
- protected void newSelectKeyMappedStatement(MappedStatement ms, EntityHelper.EntityColumn column) {
- String keyId = ms.getId() + SelectKeyGenerator.SELECT_KEY_SUFFIX;
- if (ms.getConfiguration().hasKeyGenerator(keyId)) {
- return;
- }
- Class> entityClass = getSelectReturnType(ms);
- //defaults
- Configuration configuration = ms.getConfiguration();
- KeyGenerator keyGenerator = new NoKeyGenerator();
- Boolean executeBefore = getBEFORE();
- String IDENTITY = (column.getGenerator() == null || column.getGenerator().equals("")) ? getIDENTITY() : column.getGenerator();
- SqlSource sqlSource = new RawSqlSource(configuration, IDENTITY, entityClass);
-
- MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, keyId, sqlSource, SqlCommandType.SELECT);
- statementBuilder.resource(ms.getResource());
- statementBuilder.fetchSize(null);
- statementBuilder.statementType(StatementType.STATEMENT);
- statementBuilder.keyGenerator(keyGenerator);
- statementBuilder.keyProperty(column.getProperty());
- statementBuilder.keyColumn(null);
- statementBuilder.databaseId(null);
- statementBuilder.lang(configuration.getDefaultScriptingLanuageInstance());
- statementBuilder.resultOrdered(false);
- statementBuilder.resulSets(null);
- statementBuilder.timeout(configuration.getDefaultStatementTimeout());
-
- List parameterMappings = new ArrayList();
- ParameterMap.Builder inlineParameterMapBuilder = new ParameterMap.Builder(
- configuration,
- statementBuilder.id() + "-Inline",
- entityClass,
- parameterMappings);
- statementBuilder.parameterMap(inlineParameterMapBuilder.build());
-
- List resultMaps = new ArrayList();
- ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder(
- configuration,
- statementBuilder.id() + "-Inline",
- int.class,
- new ArrayList(),
- null);
- resultMaps.add(inlineResultMapBuilder.build());
- statementBuilder.resultMaps(resultMaps);
- statementBuilder.resultSetType(null);
-
- statementBuilder.flushCacheRequired(false);
- statementBuilder.useCache(false);
- statementBuilder.cache(null);
-
- MappedStatement statement = statementBuilder.build();
- configuration.addMappedStatement(statement);
-
- MappedStatement keyStatement = configuration.getMappedStatement(keyId, false);
- configuration.addKeyGenerator(keyId, new SelectKeyGenerator(keyStatement, executeBefore));
- //keyGenerator
- try {
- MetaObject msObject = forObject(ms);
- msObject.setValue("keyGenerator", configuration.getKeyGenerator(keyId));
- } catch (Exception e) {
- //ignore
- }
- }
-}
\ No newline at end of file
diff --git a/src/main/java/com/isea533/mybatis/pagehelper/Page.java b/src/main/java/com/isea533/mybatis/pagehelper/Page.java
deleted file mode 100644
index 4175126..0000000
--- a/src/main/java/com/isea533/mybatis/pagehelper/Page.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- 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.isea533.mybatis.pagehelper;
-
-import org.apache.ibatis.session.RowBounds;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Mybatis - 分页对象
- *
- * @author liuzh/abel533/isea533
- * @version 3.3.0
- * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper
- */
-public class Page extends ArrayList {
- private static final long serialVersionUID = 1L;
-
- /**不进行count查询*/
- private static final int NO_SQL_COUNT = -1;
- /**进行count查询*/
- private static final int SQL_COUNT = 0;
- /**页码,从1开始*/
- private int pageNum;
- /**页面大小*/
- private int pageSize;
- /**起始行*/
- private int startRow;
- /**末行*/
- private int endRow;
- /**总数*/
- private long total;
- /**总页数*/
- private int pages;
- /**分页合理化*/
- private boolean reasonable;
-
- public Page(){
- super();
- }
-
- public Page(int pageNum, int pageSize) {
- this(pageNum, pageSize, SQL_COUNT);
- }
-
- public Page(int pageNum, int pageSize, boolean count) {
- this(pageNum, pageSize, count ? Page.SQL_COUNT : Page.NO_SQL_COUNT);
- }
-
- public Page(int pageNum, int pageSize, int total) {
- super(pageSize > -1 ? pageSize : 0);
- this.pageNum = pageNum;
- this.pageSize = pageSize;
- this.total = total;
- calculateStartAndEndRow();
- }
-
- public Page(RowBounds rowBounds, boolean count) {
- this(rowBounds, count ? Page.SQL_COUNT : Page.NO_SQL_COUNT);
- }
-
-
- public Page(RowBounds rowBounds, int total) {
- super(rowBounds.getLimit() > -1 ? rowBounds.getLimit() : 0);
- this.pageSize = rowBounds.getLimit();
- this.startRow = rowBounds.getOffset();
- //RowBounds方式默认不求count总数,如果想求count,可以修改这里为SQL_COUNT
- this.total = total;
- this.endRow = this.startRow + this.pageSize;
- }
-
- public List getResult() {
- return this;
- }
-
- public int getPages() {
- return pages;
- }
-
- public int getEndRow() {
- return endRow;
- }
-
- public int getPageNum() {
- return pageNum;
- }
-
- public void setPageNum(int pageNum) {
- //分页合理化,针对不合理的页码自动处理
- this.pageNum = (reasonable && pageNum <= 0) ? 1 : pageNum;
- }
-
- public int getPageSize() {
- return pageSize;
- }
-
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
-
- public int getStartRow() {
- return startRow;
- }
-
- public long getTotal() {
- return total;
- }
-
- public void setTotal(long total) {
- this.total = total;
- if (pageSize > 0) {
- pages = (int) (total / pageSize + ((total % pageSize == 0) ? 0 : 1));
- } else {
- pages = 0;
- }
- //分页合理化,针对不合理的页码自动处理
- if (reasonable && pageNum > pages) {
- pageNum = pages;
- calculateStartAndEndRow();
- }
- }
-
- public void setReasonable(boolean reasonable) {
- this.reasonable = reasonable;
- //分页合理化,针对不合理的页码自动处理
- if (this.reasonable && this.pageNum <= 0) {
- this.pageNum = 1;
- calculateStartAndEndRow();
- }
- }
-
- /**
- * 计算起止行号
- */
- private void calculateStartAndEndRow() {
- this.startRow = this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0;
- this.endRow = this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0);
- }
-
- public boolean isCount() {
- return this.total > NO_SQL_COUNT;
- }
-
- @Override
- public String toString() {
- return "Page{" +
- "pageNum=" + pageNum +
- ", pageSize=" + pageSize +
- ", startRow=" + startRow +
- ", endRow=" + endRow +
- ", total=" + total +
- ", pages=" + pages +
- '}';
- }
-}
diff --git a/src/main/java/com/isea533/mybatis/pagehelper/PageHelper.java b/src/main/java/com/isea533/mybatis/pagehelper/PageHelper.java
deleted file mode 100644
index adbf803..0000000
--- a/src/main/java/com/isea533/mybatis/pagehelper/PageHelper.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- 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.isea533.mybatis.pagehelper;
-
-import org.apache.ibatis.executor.Executor;
-import org.apache.ibatis.mapping.BoundSql;
-import org.apache.ibatis.mapping.MappedStatement;
-import org.apache.ibatis.plugin.*;
-import org.apache.ibatis.session.ResultHandler;
-import org.apache.ibatis.session.RowBounds;
-
-import java.util.List;
-import java.util.Properties;
-
-/**
- * Mybatis - 通用分页拦截器
- *
- * @author liuzh/abel533/isea533
- * @version 3.3.0
- * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper
- */
-@SuppressWarnings({"rawtypes", "unchecked"})
-@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
-public class PageHelper implements Interceptor {
- private static final ThreadLocal LOCAL_PAGE = new ThreadLocal();
- //sql工具类
- private SqlUtil SQLUTIL;
- //RowBounds参数offset作为PageNum使用 - 默认不使用
- private boolean offsetAsPageNum = false;
- //RowBounds是否进行count查询 - 默认不查询
- private boolean rowBoundsWithCount = false;
- //当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页
- private boolean pageSizeZero = false;
- //分页合理化
- private boolean reasonable = false;
- /**
- * 开始分页
- *
- * @param pageNum 页码
- * @param pageSize 每页显示数量
- */
- public static void startPage(int pageNum, int pageSize) {
- startPage(pageNum, 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);
- }
- }
- //分页合理化
- page.setReasonable(reasonable);
- return page;
- }
-
- /**
- * Mybatis拦截器方法
- *
- * @param invocation 拦截器入参
- * @return 返回执行结果
- * @throws Throwable 抛出异常
- */
- 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);
- //这种情况相当于pageSize=total
- page.setPageSize(page.size());
- //仍然要设置total
- page.setTotal(page.size());
- //返回结果仍然为Page类型 - 便于后面对接收类型的统一处理
- return page;
- }
- //简单的通过total的值来判断是否进行count查询
- if (page.isCount()) {
- BoundSql boundSql = null;
- //只有静态sql需要获取boundSql
- if (!SQLUTIL.isDynamic(ms)) {
- boundSql = ms.getBoundSql(parameterObject);
- }
- //将参数中的MappedStatement替换为新的qs
- args[0] = SQLUTIL.getCountMappedStatement(ms, boundSql);
- //查询总数
- Object result = invocation.proceed();
- //设置总数
- page.setTotal((Integer) ((List) result).get(0));
- if (page.getTotal() == 0) {
- return page;
- }
- }
- //pageSize>0的时候执行分页查询,pageSize<=0的时候不执行相当于可能只返回了一个count
- if (page.getPageSize() > 0 &&
- ((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0)
- || rowBounds != RowBounds.DEFAULT)) {
- BoundSql boundSql = null;
- //只有静态sql需要获取boundSql
- if (!SQLUTIL.isDynamic(ms)) {
- boundSql = ms.getBoundSql(parameterObject);
- }
- //将参数中的MappedStatement替换为新的qs
- args[0] = SQLUTIL.getPageMappedStatement(ms, boundSql);
- //动态sql时,boundSql在这儿通过新的ms获取
- if (boundSql == null) {
- boundSql = ((MappedStatement) args[0]).getBoundSql(parameterObject);
- }
- //判断parameterObject,然后赋值
- args[1] = SQLUTIL.setPageParameter(ms, parameterObject, boundSql, page);
- //执行分页查询
- Object result = invocation.proceed();
- //得到处理结果
- page.addAll((List) result);
- }
- //返回结果
- return page;
- }
- }
-
- /**
- * 只拦截Executor
- *
- * @param target
- * @return
- */
- public Object plugin(Object target) {
- if (target instanceof Executor) {
- return Plugin.wrap(target, this);
- } else {
- return target;
- }
- }
-
- /**
- * 设置属性值
- *
- * @param p 属性值
- */
- public void setProperties(Properties p) {
- //数据库方言
- String dialect = p.getProperty("dialect");
- SQLUTIL = new SqlUtil(dialect);
- //offset作为PageNum使用
- String offsetAsPageNum = p.getProperty("offsetAsPageNum");
- this.offsetAsPageNum = Boolean.parseBoolean(offsetAsPageNum);
- //RowBounds方式是否做count查询
- String rowBoundsWithCount = p.getProperty("rowBoundsWithCount");
- this.rowBoundsWithCount = Boolean.parseBoolean(rowBoundsWithCount);
- //当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页
- String pageSizeZero = p.getProperty("pageSizeZero");
- this.pageSizeZero = Boolean.parseBoolean(pageSizeZero);
- //分页合理化,true开启,如果分页参数不合理会自动修正。默认false不启用
- String reasonable = p.getProperty("reasonable");
- this.reasonable = Boolean.parseBoolean(reasonable);
- }
-}
diff --git a/src/main/java/com/isea533/mybatis/pagehelper/PageInfo.java b/src/main/java/com/isea533/mybatis/pagehelper/PageInfo.java
deleted file mode 100644
index d5a6930..0000000
--- a/src/main/java/com/isea533/mybatis/pagehelper/PageInfo.java
+++ /dev/null
@@ -1,272 +0,0 @@
-package com.isea533.mybatis.pagehelper;
-
-import java.util.List;
-
-/**
- * 对Page结果进行包装
- *
- * 新增分页的多项属性,主要参考:http://bbs.csdn.net/topics/360010907
- *
- * @author liuzh/abel533/isea533
- * @version 3.3.0
- * @since 3.2.2
- * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper
- */
-@SuppressWarnings({ "rawtypes", "unchecked" })
-public class PageInfo {
- //当前页
- private int pageNum;
- //每页的数量
- private int pageSize;
- //当前页的数量
- private int size;
- //由于startRow和endRow不常用,这里说个具体的用法
- //可以在页面中"显示startRow到endRow 共size条数据"
-
- //当前页面第一个元素在数据库中的行号
- private int startRow;
- //当前页面最后一个元素在数据库中的行号
- private int endRow;
- //总记录数
- private long total;
- //总页数
- private int pages;
- //结果集
- private List list;
-
- //第一页
- private int firstPage;
- //前一页
- private int prePage;
- //下一页
- private int nextPage;
- //最后一页
- private int lastPage;
-
- //是否为第一页
- private boolean isFirstPage = false;
- //是否为最后一页
- private boolean isLastPage = false;
- //是否有前一页
- private boolean hasPreviousPage = false;
- //是否有下一页
- private boolean hasNextPage = false;
- //导航页码数
- private int navigatePages;
- //所有导航页号
- private int[] navigatepageNums;
-
- /**
- * 包装Page对象
- *
- * @param list
- */
- public PageInfo(List list) {
- this(list, 8);
- }
-
- /**
- * 包装Page对象
- *
- * @param list page结果
- * @param navigatePages 页码数量
- */
- public PageInfo(List list, int navigatePages) {
- if (list instanceof Page) {
- Page page = (Page) list;
- this.pageNum = page.getPageNum();
- this.pageSize = page.getPageSize();
-
- this.total = page.getTotal();
- this.pages = page.getPages();
- this.list = page;
- this.size = page.size();
- //由于结果是>startRow的,所以实际的需要+1
- if (this.size == 0) {
- this.startRow = 0;
- this.endRow = 0;
- } else {
- this.startRow = page.getStartRow() + 1;
- //计算实际的endRow(最后一页的时候特殊)
- this.endRow = this.startRow - 1 + this.size;
- }
- this.navigatePages = navigatePages;
- //计算导航页
- calcNavigatepageNums();
- //计算前后页,第一页,最后一页
- calcPage();
- //判断页面边界
- judgePageBoudary();
- }
- }
-
- /**
- * 计算导航页
- */
- private void calcNavigatepageNums() {
- //当总页数小于或等于导航页码数时
- if (pages <= navigatePages) {
- navigatepageNums = new int[pages];
- for (int i = 0; i < pages; i++) {
- navigatepageNums[i] = i + 1;
- }
- } else { //当总页数大于导航页码数时
- navigatepageNums = new int[navigatePages];
- int startNum = pageNum - navigatePages / 2;
- int endNum = pageNum + navigatePages / 2;
-
- if (startNum < 1) {
- startNum = 1;
- //(最前navigatePages页
- for (int i = 0; i < navigatePages; i++) {
- navigatepageNums[i] = startNum++;
- }
- } else if (endNum > pages) {
- endNum = pages;
- //最后navigatePages页
- for (int i = navigatePages - 1; i >= 0; i--) {
- navigatepageNums[i] = endNum--;
- }
- } else {
- //所有中间页
- for (int i = 0; i < navigatePages; i++) {
- navigatepageNums[i] = startNum++;
- }
- }
- }
- }
-
- /**
- * 计算前后页,第一页,最后一页
- */
- private void calcPage() {
- if (navigatepageNums != null && navigatepageNums.length > 0) {
- firstPage = navigatepageNums[0];
- lastPage = navigatepageNums[navigatepageNums.length - 1];
- if (pageNum > 1) {
- prePage = pageNum - 1;
- }
- if (pageNum < pages) {
- nextPage = pageNum + 1;
- }
- }
- }
-
- /**
- * 判定页面边界
- */
- private void judgePageBoudary() {
- isFirstPage = pageNum == 1;
- isLastPage = pageNum == pages && pageNum != 1;
- hasPreviousPage = pageNum > 1;
- hasNextPage = pageNum < pages;
- }
-
- public void setPageNum(int pageNum) {
- this.pageNum = pageNum;
- }
-
- public int getPageNum() {
- return pageNum;
- }
-
- public int getPageSize() {
- return pageSize;
- }
-
- public int getSize() {
- return size;
- }
-
- public int getStartRow() {
- return startRow;
- }
-
- public int getEndRow() {
- return endRow;
- }
-
- public long getTotal() {
- return total;
- }
-
- public int getPages() {
- return pages;
- }
-
- public List getList() {
- return list;
- }
-
- public int getFirstPage() {
- return firstPage;
- }
-
- public int getPrePage() {
- return prePage;
- }
-
- public int getNextPage() {
- return nextPage;
- }
-
- public int getLastPage() {
- return lastPage;
- }
-
- public boolean isIsFirstPage() {
- return isFirstPage;
- }
-
- public boolean isIsLastPage() {
- return isLastPage;
- }
-
- public boolean isHasPreviousPage() {
- return hasPreviousPage;
- }
-
- public boolean isHasNextPage() {
- return hasNextPage;
- }
-
- public int getNavigatePages() {
- return navigatePages;
- }
-
- public int[] getNavigatepageNums() {
- return navigatepageNums;
- }
-
- @Override
- public String toString() {
- final StringBuffer sb = new StringBuffer("PageInfo{");
- sb.append("pageNum=").append(pageNum);
- sb.append(", pageSize=").append(pageSize);
- sb.append(", size=").append(size);
- sb.append(", startRow=").append(startRow);
- sb.append(", endRow=").append(endRow);
- sb.append(", total=").append(total);
- sb.append(", pages=").append(pages);
- sb.append(", list=").append(list);
- sb.append(", firstPage=").append(firstPage);
- sb.append(", prePage=").append(prePage);
- sb.append(", nextPage=").append(nextPage);
- sb.append(", lastPage=").append(lastPage);
- sb.append(", isFirstPage=").append(isFirstPage);
- sb.append(", isLastPage=").append(isLastPage);
- sb.append(", hasPreviousPage=").append(hasPreviousPage);
- sb.append(", hasNextPage=").append(hasNextPage);
- sb.append(", navigatePages=").append(navigatePages);
- sb.append(", navigatepageNums=");
- if (navigatepageNums == null) sb.append("null");
- else {
- sb.append('[');
- for (int i = 0; i < navigatepageNums.length; ++i)
- sb.append(i == 0 ? "" : ", ").append(navigatepageNums[i]);
- sb.append(']');
- }
- sb.append('}');
- return sb.toString();
- }
-}
diff --git a/src/main/java/com/isea533/mybatis/pagehelper/SqlParser.java b/src/main/java/com/isea533/mybatis/pagehelper/SqlParser.java
deleted file mode 100644
index a46694b..0000000
--- a/src/main/java/com/isea533/mybatis/pagehelper/SqlParser.java
+++ /dev/null
@@ -1,242 +0,0 @@
-package com.isea533.mybatis.pagehelper;
-
-import net.sf.jsqlparser.JSQLParserException;
-import net.sf.jsqlparser.expression.Alias;
-import net.sf.jsqlparser.parser.CCJSqlParserUtil;
-import net.sf.jsqlparser.schema.Column;
-import net.sf.jsqlparser.statement.Statement;
-import net.sf.jsqlparser.statement.select.*;
-import org.apache.ibatis.mapping.BoundSql;
-import org.apache.ibatis.mapping.MappedStatement;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * sql解析类,使用该类时,必须引入jsqlparser-x.x.x.jar
- *
- * @author liuzh
- */
-@SuppressWarnings("rawtypes")
-public class SqlParser implements SqlUtil.Parser {
- private static final List COUNT_ITEM;
- private static final Alias TABLE_ALIAS;
- private SqlUtil.Parser simpleParser;
-
- static {
- COUNT_ITEM = new ArrayList();
- COUNT_ITEM.add(new SelectExpressionItem(new Column("count(*)")));
-
- TABLE_ALIAS = new Alias("table_count");
- TABLE_ALIAS.setUseAs(false);
- }
-
- //缓存已经修改过的sql
- private Map CACHE = new ConcurrentHashMap();
-
- public SqlParser(SqlUtil.Dialect dialect) {
- simpleParser = SqlUtil.SimpleParser.newParser(dialect);
- }
-
- public void isSupportedSql(String sql) {
- simpleParser.isSupportedSql(sql);
- }
-
- public String getCountSql(String sql) {
- //校验是否支持该sql
- isSupportedSql(sql);
- return parse(sql);
- }
-
- public String getPageSql(String sql) {
- return simpleParser.getPageSql(sql);
- }
-
- public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {
- return simpleParser.setPageParameter(ms, parameterObject, boundSql, page);
- }
-
- public String parse(String sql) {
- if (CACHE.get(sql) != null) {
- return CACHE.get(sql);
- }
- Statement stmt = null;
- try {
- stmt = CCJSqlParserUtil.parse(sql);
- } catch (JSQLParserException e) {
- //无法解析的直接返回原sql
- CACHE.put(sql, sql);
- return sql;
- }
- Select select = (Select) stmt;
- SelectBody selectBody = select.getSelectBody();
- //处理body
- processSelectBody(selectBody);
- //处理with
- processWithItemsList(select.getWithItemsList());
- //处理为count查询
- sqlToCount(select);
- String result = select.toString();
- CACHE.put(sql, result);
- return result;
- }
-
- /**
- * 将sql转换为count查询
- *
- * @param select
- */
- public void sqlToCount(Select select) {
- SelectBody selectBody = select.getSelectBody();
- // select中包含参数时在else中处理
- // select中包含group by时在else中处理
- if (selectBody instanceof PlainSelect
- && !selectItemsHashParameters(((PlainSelect) selectBody).getSelectItems())
- && ((PlainSelect) selectBody).getGroupByColumnReferences() == null) {
- ((PlainSelect) selectBody).setSelectItems(COUNT_ITEM);
- } else {
- PlainSelect plainSelect = new PlainSelect();
- SubSelect subSelect = new SubSelect();
- subSelect.setSelectBody(selectBody);
- subSelect.setAlias(TABLE_ALIAS);
- plainSelect.setFromItem(subSelect);
- plainSelect.setSelectItems(COUNT_ITEM);
- select.setSelectBody(plainSelect);
- }
- }
-
- /**
- * 处理selectBody去除Order by
- *
- * @param selectBody
- */
- public void processSelectBody(SelectBody selectBody) {
- if (selectBody instanceof PlainSelect) {
- processPlainSelect((PlainSelect) selectBody);
- } else if (selectBody instanceof WithItem) {
- WithItem withItem = (WithItem) selectBody;
- if (withItem.getSelectBody() != null) {
- processSelectBody(withItem.getSelectBody());
- }
- } else {
- SetOperationList operationList = (SetOperationList) selectBody;
- if (operationList.getPlainSelects() != null && operationList.getPlainSelects().size() > 0) {
- List plainSelects = operationList.getPlainSelects();
- for (PlainSelect plainSelect : plainSelects) {
- processPlainSelect(plainSelect);
- }
- }
- if (!orderByHashParameters(operationList.getOrderByElements())) {
- operationList.setOrderByElements(null);
- }
- }
- }
-
- /**
- * 处理PlainSelect类型的selectBody
- *
- * @param plainSelect
- */
- public void processPlainSelect(PlainSelect plainSelect) {
- if (!orderByHashParameters(plainSelect.getOrderByElements())) {
- plainSelect.setOrderByElements(null);
- }
- if (plainSelect.getFromItem() != null) {
- processFromItem(plainSelect.getFromItem());
- }
- if (plainSelect.getJoins() != null && plainSelect.getJoins().size() > 0) {
- List joins = plainSelect.getJoins();
- for (Join join : joins) {
- if (join.getRightItem() != null) {
- processFromItem(join.getRightItem());
- }
- }
- }
- }
-
- /**
- * 处理WithItem
- *
- * @param withItemsList
- */
- public void processWithItemsList(List withItemsList) {
- if (withItemsList != null && withItemsList.size() > 0) {
- for (WithItem item : withItemsList) {
- processSelectBody(item.getSelectBody());
- }
- }
- }
-
- /**
- * 处理子查询
- *
- * @param fromItem
- */
- public void processFromItem(FromItem fromItem) {
- if (fromItem instanceof SubJoin) {
- SubJoin subJoin = (SubJoin) fromItem;
- if (subJoin.getJoin() != null) {
- if (subJoin.getJoin().getRightItem() != null) {
- processFromItem(subJoin.getJoin().getRightItem());
- }
- }
- if (subJoin.getLeft() != null) {
- processFromItem(subJoin.getLeft());
- }
- } else if (fromItem instanceof SubSelect) {
- SubSelect subSelect = (SubSelect) fromItem;
- if (subSelect.getSelectBody() != null) {
- processSelectBody(subSelect.getSelectBody());
- }
- } else if (fromItem instanceof ValuesList) {
-
- } else if (fromItem instanceof LateralSubSelect) {
- LateralSubSelect lateralSubSelect = (LateralSubSelect) fromItem;
- if (lateralSubSelect.getSubSelect() != null) {
- SubSelect subSelect = (SubSelect) (lateralSubSelect.getSubSelect());
- if (subSelect.getSelectBody() != null) {
- processSelectBody(subSelect.getSelectBody());
- }
- }
- }
- //Table时不用处理
- }
-
- /**
- * 判断Orderby是否包含参数,有参数的不能去
- *
- * @param orderByElements
- * @return
- */
- public boolean orderByHashParameters(List orderByElements) {
- if (orderByElements == null) {
- return false;
- }
- for (OrderByElement orderByElement : orderByElements) {
- if (orderByElement.toString().contains("?")) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * 判断selectItems是否包含参数,有参数的不能去
- *
- * @param selectItems
- * @return
- */
- public boolean selectItemsHashParameters(List selectItems) {
- if (selectItems == null) {
- return false;
- }
- for (SelectItem selectItem : selectItems) {
- if (selectItem.toString().contains("?")) {
- return true;
- }
- }
- return false;
- }
-}
diff --git a/src/main/java/com/isea533/mybatis/pagehelper/SqlUtil.java b/src/main/java/com/isea533/mybatis/pagehelper/SqlUtil.java
deleted file mode 100644
index b603b25..0000000
--- a/src/main/java/com/isea533/mybatis/pagehelper/SqlUtil.java
+++ /dev/null
@@ -1,549 +0,0 @@
-/*
- * 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.isea533.mybatis.pagehelper;
-
-import org.apache.ibatis.builder.SqlSourceBuilder;
-import org.apache.ibatis.mapping.*;
-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.scripting.xmltags.DynamicContext;
-import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
-import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
-import org.apache.ibatis.scripting.xmltags.SqlNode;
-import org.apache.ibatis.session.Configuration;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Mybatis - sql工具,获取分页和count的MappedStatement,设置分页参数
- *
- * @author liuzh/abel533/isea533
- * @since 3.3.0
- * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper
- */
-@SuppressWarnings({"rawtypes", "unchecked"})
-public class SqlUtil {
- private static final List EMPTY_RESULTMAPPING = new ArrayList(0);
- //分页的id后缀
- private static final String SUFFIX_PAGE = "_PageHelper";
- //count查询的id后缀
- 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 ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
- private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
-
- /**
- * 反射对象,增加对低版本Mybatis的支持
- *
- * @param object 反射对象
- * @return
- */
- private static MetaObject forObject(Object object) {
- return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
- }
-
- private SqlUtil.Parser sqlParser;
-
- //数据库方言 - 使用枚举限制数据库类型
- public enum Dialect {
- mysql, mariadb, sqlite, oracle, hsqldb, postgresql
- }
-
- /**
- * 构造方法
- *
- * @param strDialect
- */
- public SqlUtil(String strDialect) {
- if (strDialect == null || "".equals(strDialect)) {
- throw new IllegalArgumentException("Mybatis分页插件无法获取dialect参数!");
- }
- try {
- Dialect dialect = Dialect.valueOf(strDialect);
- String sqlParserClass = this.getClass().getPackage().getName() + ".SqlParser";
- try {
- //使用SqlParser必须引入jsqlparser-x.x.x.jar
- Class.forName("net.sf.jsqlparser.statement.select.Select");
- sqlParser = (Parser) Class.forName(sqlParserClass).getConstructor(Dialect.class).newInstance(dialect);
- } catch (Exception e) {
- //找不到时,不用处理
- }
- if (sqlParser == null) {
- sqlParser = SimpleParser.newParser(dialect);
- }
- } catch (IllegalArgumentException e) {
- String dialects = null;
- for (Dialect d : Dialect.values()) {
- if (dialects == null) {
- dialects = d.toString();
- } else {
- dialects += "," + d;
- }
- }
- throw new IllegalArgumentException("Mybatis分页插件dialect参数值错误,可选值为[" + dialects + "]");
- }
- }
-
- /**
- * 设置分页参数
- *
- * @param parameterObject
- * @param boundSql
- * @param page
- * @return
- */
- public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {
- return sqlParser.setPageParameter(ms, parameterObject, boundSql, page);
- }
-
- /**
- * 获取count查询的MappedStatement
- *
- * @param ms
- * @param boundSql
- * @return
- */
- public MappedStatement getCountMappedStatement(MappedStatement ms, BoundSql boundSql) {
- return getMappedStatement(ms, boundSql, SUFFIX_COUNT);
- }
-
- /**
- * 获取分页查询的MappedStatement
- *
- * @param ms
- * @param boundSql
- * @return
- */
- public MappedStatement getPageMappedStatement(MappedStatement ms, BoundSql boundSql) {
- return getMappedStatement(ms, boundSql, SUFFIX_PAGE);
- }
-
- /**
- * 处理SQL
- */
- public static interface Parser {
- void isSupportedSql(String sql);
-
- String getCountSql(String sql);
-
- String getPageSql(String sql);
-
- Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page);
- }
-
- public static abstract class SimpleParser implements Parser {
- public static Parser newParser(Dialect dialect) {
- Parser parser = null;
- switch (dialect) {
- case mysql:
- case mariadb:
- case sqlite:
- parser = new MysqlParser();
- break;
- case oracle:
- parser = new OracleParser();
- break;
- case hsqldb:
- parser = new HsqldbParser();
- break;
- case postgresql:
- default:
- parser = new PostgreSQLParser();
- }
- return parser;
- }
-
- public void isSupportedSql(String sql) {
- if (sql.trim().toUpperCase().endsWith("FOR UPDATE")) {
- throw new RuntimeException("分页插件不支持包含for update的sql");
- }
- }
-
- /**
- * 获取总数sql - 如果要支持其他数据库,修改这里就可以
- *
- * @param sql 原查询sql
- * @return 返回count查询sql
- */
- public String getCountSql(final String sql) {
- isSupportedSql(sql);
- StringBuilder stringBuilder = new StringBuilder(sql.length() + 40);
- stringBuilder.append("select count(*) from (");
- stringBuilder.append(sql);
- stringBuilder.append(") tmp_count");
- return stringBuilder.toString();
- }
-
- /**
- * 获取分页sql - 如果要支持其他数据库,修改这里就可以
- *
- * @param sql 原查询sql
- * @return 返回分页sql
- */
- public abstract String getPageSql(String sql);
-
- public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {
- Map paramMap = null;
- if (parameterObject == null) {
- paramMap = new HashMap();
- } else if (parameterObject instanceof Map) {
- paramMap = (Map) parameterObject;
- } else {
- paramMap = new HashMap();
- //动态sql时的判断条件不会出现在ParameterMapping中,但是必须有,所以这里需要收集所有的getter属性
- //TypeHandlerRegistry可以直接处理的会作为一个直接使用的对象进行处理
- boolean hasTypeHandler = ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass());
- if (!hasTypeHandler) {
- MetaObject metaObject = forObject(parameterObject);
- for (String name : metaObject.getGetterNames()) {
- paramMap.put(name, metaObject.getValue(name));
- }
- }
- //下面这段方法,主要解决一个常见类型的参数时的问题
- if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) {
- for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
- String name = parameterMapping.getProperty();
- if (!name.equals(PAGEPARAMETER_FIRST)
- && !name.equals(PAGEPARAMETER_SECOND)
- && paramMap.get(name) == null) {
- if (hasTypeHandler
- || parameterMapping.getJavaType().isAssignableFrom(parameterObject.getClass())) {
- paramMap.put(name, parameterObject);
- }
- }
- }
- }
- }
- return paramMap;
- }
- }
-
- //Mysql
- private static class MysqlParser extends SimpleParser {
- @Override
- public String getPageSql(String sql) {
- StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
- sqlBuilder.append(sql);
- sqlBuilder.append(" limit ?,?");
- return sqlBuilder.toString();
- }
-
- @Override
- public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {
- Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);
- paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
- paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
- return paramMap;
- }
- }
-
- //Oracle
- private static class OracleParser extends SimpleParser {
- @Override
- public String getPageSql(String sql) {
- StringBuilder sqlBuilder = new StringBuilder(sql.length() + 120);
- sqlBuilder.append("select * from ( select tmp_page.*, rownum row_id from ( ");
- sqlBuilder.append(sql);
- sqlBuilder.append(" ) tmp_page where rownum <= ? ) where row_id > ?");
- return sqlBuilder.toString();
- }
-
- @Override
- public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {
- Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);
- paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow());
- paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow());
- return paramMap;
- }
- }
-
- //Oracle
- private static class HsqldbParser extends SimpleParser {
- @Override
- public String getPageSql(String sql) {
- StringBuilder sqlBuilder = new StringBuilder(sql.length() + 20);
- sqlBuilder.append(sql);
- sqlBuilder.append(" limit ? offset ?");
- return sqlBuilder.toString();
- }
-
- @Override
- public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {
- Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);
- paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize());
- paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow());
- return paramMap;
- }
- }
-
- //PostgreSQL
- private static class PostgreSQLParser extends SimpleParser {
- @Override
- public String getPageSql(String sql) {
- StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
- sqlBuilder.append(sql);
- sqlBuilder.append(" limit ? offset ?");
- return sqlBuilder.toString();
- }
-
- @Override
- public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {
- Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);
- paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize());
- paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow());
- return paramMap;
- }
- }
-
- /**
- * 自定义简单SqlSource
- */
- 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;
- }
- }
-
- /**
- * 自定义动态SqlSource
- */
- private class MyDynamicSqlSource implements SqlSource {
- private Configuration configuration;
- private SqlNode rootSqlNode;
- /**
- * 用于区分动态的count查询或分页查询
- */
- private Boolean count;
-
- public MyDynamicSqlSource(Configuration configuration, SqlNode rootSqlNode, Boolean count) {
- this.configuration = configuration;
- this.rootSqlNode = rootSqlNode;
- this.count = count;
- }
-
- public BoundSql getBoundSql(Object parameterObject) {
- DynamicContext context = new DynamicContext(configuration, parameterObject);
- rootSqlNode.apply(context);
- SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
- Class> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
- SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
- BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
- //设置条件参数
- for (Map.Entry entry : context.getBindings().entrySet()) {
- boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
- }
- BoundSqlSqlSource boundSqlSqlSource = new BoundSqlSqlSource(boundSql);
- if (count) {
- boundSqlSqlSource = getCountSqlSource(boundSqlSqlSource);
- } else {
- boundSqlSqlSource = getPageSqlSource(configuration, boundSqlSqlSource);
- }
- return boundSqlSqlSource.getBoundSql();
- }
- }
-
-
- /**
- * 获取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, getNewSqlSource(ms, new BoundSqlSqlSource(boundSql), suffix), suffix);
- try {
- ms.getConfiguration().addMappedStatement(qs);
- } catch (Exception e) {
- //ignore
- }
- }
- return qs;
- }
-
- /**
- * 新建count查询和分页查询的MappedStatement
- *
- * @param ms
- * @param newSqlSource
- * @param suffix
- * @return
- */
- private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource, String suffix) {
- String id = ms.getId() + suffix;
- 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 {
- //count查询返回值int
- List resultMaps = new ArrayList();
- 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();
- }
-
- /**
- * 判断当前执行的是否为动态sql
- *
- * @param ms
- * @return
- */
- public boolean isDynamic(MappedStatement ms) {
- return ms.getSqlSource() instanceof DynamicSqlSource;
- }
-
- /**
- * 获取新的sqlSource
- *
- * @param ms
- * @param newSqlSource
- * @param suffix
- * @return
- */
- private SqlSource getNewSqlSource(MappedStatement ms, BoundSqlSqlSource newSqlSource, String suffix) {
- //从XMLLanguageDriver.java和XMLScriptBuilder.java可以看出只有两种SqlSource
- //如果是动态sql
- if (isDynamic(ms)) {
- MetaObject msObject = forObject(ms);
- SqlNode sqlNode = (SqlNode) msObject.getValue("sqlSource.rootSqlNode");
- MixedSqlNode mixedSqlNode = null;
- if (sqlNode instanceof MixedSqlNode) {
- mixedSqlNode = (MixedSqlNode) sqlNode;
- } else {
- List contents = new ArrayList(1);
- contents.add(sqlNode);
- mixedSqlNode = new MixedSqlNode(contents);
- }
- return new MyDynamicSqlSource(ms.getConfiguration(), mixedSqlNode, suffix == SUFFIX_COUNT);
- }
- //如果是静态分页sql
- else if (suffix == SUFFIX_PAGE) {
- //改为分页sql
- return getPageSqlSource(ms.getConfiguration(), newSqlSource);
- }
- //如果是静态count-sql
- else {
- return getCountSqlSource(newSqlSource);
- }
- }
-
- /**
- * 获取分页的sqlSource
- *
- * @param configuration
- * @param newSqlSource
- * @return
- */
- private BoundSqlSqlSource getPageSqlSource(Configuration configuration, BoundSqlSqlSource newSqlSource) {
- String sql = newSqlSource.getBoundSql().getSql();
- //改为分页sql
- MetaObject sqlObject = forObject(newSqlSource);
- sqlObject.setValue("boundSql.sql", sqlParser.getPageSql(sql));
- //添加参数映射
- List newParameterMappings = new ArrayList();
- newParameterMappings.addAll(newSqlSource.getBoundSql().getParameterMappings());
- newParameterMappings.add(new ParameterMapping.Builder(configuration, PAGEPARAMETER_FIRST, Integer.class).build());
- newParameterMappings.add(new ParameterMapping.Builder(configuration, PAGEPARAMETER_SECOND, Integer.class).build());
- sqlObject.setValue("boundSql.parameterMappings", newParameterMappings);
- return newSqlSource;
- }
-
- /**
- * 获取count的sqlSource
- *
- * @param newSqlSource
- * @return
- */
- private BoundSqlSqlSource getCountSqlSource(BoundSqlSqlSource newSqlSource) {
- String sql = newSqlSource.getBoundSql().getSql();
- MetaObject sqlObject = forObject(newSqlSource);
- sqlObject.setValue("boundSql.sql", sqlParser.getCountSql(sql));
- return newSqlSource;
- }
-
- /**
- * 测试[控制台输出]count和分页sql
- *
- * @param dialet 数据库类型
- * @param originalSql 原sql
- */
- public static void testSql(String dialet, String originalSql) {
- SqlUtil sqlUtil = new SqlUtil(dialet);
- String countSql = sqlUtil.sqlParser.getCountSql(originalSql);
- System.out.println(countSql);
- String pageSql = sqlUtil.sqlParser.getPageSql(originalSql);
- System.out.println(pageSql);
- }
-}
diff --git a/src/main/java/com/isea533/mybatis/service/BaseService.java b/src/main/java/com/isea533/mybatis/service/BaseService.java
deleted file mode 100644
index fdf6393..0000000
--- a/src/main/java/com/isea533/mybatis/service/BaseService.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.isea533.mybatis.service;
-
-import com.isea533.mybatis.mapperhelper.Mapper;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-/**
- * Created by liuzh on 2014/12/11.
- */
-@Service
-public class BaseService {
-
- @Autowired
- protected Mapper mapper;
-
-}
diff --git a/src/main/java/com/isea533/mybatis/service/DemoService.java b/src/main/java/com/isea533/mybatis/service/DemoService.java
index 76785b0..a1f0978 100644
--- a/src/main/java/com/isea533/mybatis/service/DemoService.java
+++ b/src/main/java/com/isea533/mybatis/service/DemoService.java
@@ -1,9 +1,10 @@
package com.isea533.mybatis.service;
+import com.github.pagehelper.PageHelper;
+import com.isea533.mybatis.mapper.Country2Mapper;
import com.isea533.mybatis.mapper.CountryMapper;
import com.isea533.mybatis.model.Country;
import com.isea533.mybatis.model.Country2;
-import com.isea533.mybatis.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -16,10 +17,13 @@
* @author liuzh
*/
@Service
-public class DemoService extends BaseService {
+public class DemoService {
@Autowired
private CountryMapper countryMapper;
+ @Autowired
+ private Country2Mapper mapper;
+
private JdbcTemplate jdbcTemplate;
@Autowired
diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml
index 20d4d69..f148304 100644
--- a/src/main/resources/applicationContext.xml
+++ b/src/main/resources/applicationContext.xml
@@ -34,18 +34,20 @@
-
-
+
+
- dialect=hsqldb
- reasonable=true
+ mappers=tk.mybatis.mapper.common.Mapper
+ IDENTITY=MYSQL
+ notEmpty=true
@@ -54,7 +56,7 @@
-
+
@@ -80,14 +82,4 @@
-
-
-
-
- com.isea533.mybatis.mapperhelper.Mapper
-
-
-
-
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/jsp/index.jsp b/src/main/webapp/WEB-INF/jsp/index.jsp
index 57dc8fb..847ea09 100644
--- a/src/main/webapp/WEB-INF/jsp/index.jsp
+++ b/src/main/webapp/WEB-INF/jsp/index.jsp
@@ -150,20 +150,7 @@
diff --git a/src/test/java/com/isea533/mybatis/test/BasicTest.java b/src/test/java/com/isea533/mybatis/test/BasicTest.java
new file mode 100644
index 0000000..06f465b
--- /dev/null
+++ b/src/test/java/com/isea533/mybatis/test/BasicTest.java
@@ -0,0 +1,13 @@
+package com.isea533.mybatis.test;
+
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ * Created by liuzh on 2015/3/7.
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:applicationContext.xml")
+public class BasicTest {
+}
diff --git a/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java b/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java
new file mode 100644
index 0000000..294dbdd
--- /dev/null
+++ b/src/test/java/com/isea533/mybatis/test/NoAutoWiredMapperTest.java
@@ -0,0 +1,22 @@
+package com.isea533.mybatis.test;
+
+import com.isea533.mybatis.mapper.UserInfoMapper;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * Created by liuzh on 2015/3/7.
+ */
+public class NoAutoWiredMapperTest extends BasicTest {
+
+ @Autowired
+ private SqlSession sqlSession;
+
+ @Test
+ public void test(){
+ UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
+ int count = userInfoMapper.selectCount(null);
+ System.out.println(count);
+ }
+}