Mybatis-PageHelper分頁--IIF函數坑

最近在開發一個頁面分頁的後端代碼,使用的分頁是mybatis的pagehelper jar組件,其中用到的版本是5.0.1 即 pagehelper-5.0.1.jar;分頁時查詢SQL語句

select a.* from (SELECT b.id,b.cid,b.customerId,c.opportunityId,b.customerName,b.detailAddress,b.stageId,b.visitDate,b.isIntention,b.productIds,b.creatorId,b.creatorName,b.contactsId,b.contactsName,b.visitItems,b.visitType,b.accompanyVisitorIds,b.createTime,b.modifyTime,c.longitude as cusLongitude,c.latitude as cusLatitude,2 as customerType,c.salesId from tCustomerVisitPlan b inner join tCustomer c on b.customerId = c.id WHERE b.cid=? and b.creatorId=? and b.visitDate=? AND b.isDel=0 UNION ALL SELECT b.id,b.cid,c.customerId,b.opportunityId,b.opportunityName as customerName,b.detailAddress,b.stageId,b.visitDate,1 as isIntention,b.productIds,b.creatorId,b.creatorName,b.contactsId,b.contactsName,b.visitItems,b.visitType,b.accompanyVisitorIds,b.createTime,b.modifyTime,c.longitude as cusLongitude,c.latitude as cusLatitude,1 as customerType,IIf (ISNULL(c.customerId, 0) > 0,d.salesId,c.salesId) AS salesId from tOpportunityVisitPlan b inner join tOpportunity c on b.opportunityId = c.id left join tCustomer d on c.customerId = d.id WHERE b.cid=? and b.creatorId=? and b.visitDate=? AND b.isDel=0) as a order by a.modifyTime desc,a.createTime desc

看到此SQL貌似除了語句長了一些,其他麼有什麼問題,但是在具體執行查詢時竟然報錯了~~,以下是錯誤截圖:
在這裏插入圖片描述
**

通過錯誤截圖分析在執行分頁查詢SQL時,pagehelper中一個PageInterceptor類攔截器會攔截處理sql語句**

@Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();
            MappedStatement ms = (MappedStatement) args[0];
            Object parameter = args[1];
            RowBounds rowBounds = (RowBounds) args[2];
            ResultHandler resultHandler = (ResultHandler) args[3];
            Executor executor = (Executor) invocation.getTarget();
            CacheKey cacheKey;
            BoundSql boundSql;
            //由於邏輯關係,只會進入一次
            if(args.length == 4){
                //4 個參數時
                boundSql = ms.getBoundSql(parameter);
                cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            } else {
                //6 個參數時
                cacheKey = (CacheKey) args[4];
                boundSql = (BoundSql) args[5];
            }
            List resultList;
            //調用方法判斷是否需要進行分頁,如果不需要,直接返回結果
            if (!dialect.skip(ms, parameter, rowBounds)) {
                //反射獲取動態參數
                Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
                //判斷是否需要進行 count 查詢
                if (dialect.beforeCount(ms, parameter, rowBounds)) {
                    //創建 count 查詢的緩存 key
                    CacheKey countKey = executor.createCacheKey(ms, parameter, RowBounds.DEFAULT, boundSql);
                    countKey.update(MSUtils.COUNT);
                    MappedStatement countMs = msCountMap.get(countKey);
                    if (countMs == null) {
                        //根據當前的 ms 創建一個返回值爲 Long 類型的 ms
                        countMs = MSUtils.newCountMappedStatement(ms);
                        msCountMap.put(countKey, countMs);
                    }
                    //調用方言獲取 count sql
                    String countSql = dialect.getCountSql(ms, boundSql, parameter, rowBounds, countKey);
                    countKey.update(countSql);
                    BoundSql countBoundSql = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter);
                    //當使用動態 SQL 時,可能會產生臨時的參數,這些參數需要手動設置到新的 BoundSql 中
                    for (String key : additionalParameters.keySet()) {
                        countBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
                    }
                    //執行 count 查詢
                    Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
                    Long count = (Long) ((List) countResultList).get(0);
                    //處理查詢總數
                    //返回 true 時繼續分頁查詢,false 時直接返回
                    if (!dialect.afterCount(count, parameter, rowBounds)) {
                        //當查詢總數爲 0 時,直接返回空的結果
                        return dialect.afterPage(new ArrayList(), parameter, rowBounds);
                    }
                }
                //判斷是否需要進行分頁查詢
                if (dialect.beforePage(ms, parameter, rowBounds)) {
                    //生成分頁的緩存 key
                    CacheKey pageKey = cacheKey;
                    //處理參數對象
                    parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
                    //調用方言獲取分頁 sql
                    String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
                    BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);
                    //設置動態參數
                    for (String key : additionalParameters.keySet()) {
                        pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
                    }
                    //執行分頁查詢
                    resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
                } else {
                    //不執行分頁的情況下,也不執行內存分頁
                    resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
                }
            } else {
                //rowBounds用參數值,不使用分頁插件處理時,仍然支持默認的內存分頁
                resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
            }
            return dialect.afterPage(resultList, parameter, rowBounds);
        } finally {
            dialect.afterAll();
        }
    }

繼續往下追蹤PageHelper的getCountSql

@Override
public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
return autoDialect.getDelegate().getCountSql(ms, boundSql, parameterObject, rowBounds, countKey);
}

繼續往下追蹤SqlServerDialect的getCountSql

@Override
    public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
        String sql = boundSql.getSql();
        String cacheSql = CACHE_COUNTSQL.get(sql);
        if (cacheSql != null) {
            return cacheSql;
        } else {
            cacheSql = sql;
        }
        cacheSql = cacheSql.replaceAll("((?i)with\\s*\\(nolock\\))", WITHNOLOCK);
        cacheSql = countSqlParser.getSmartCountSql(cacheSql);
        cacheSql = cacheSql.replaceAll(WITHNOLOCK, " with(nolock)");
        CACHE_COUNTSQL.put(sql, cacheSql);
        return cacheSql;
    }
**繼續往下追蹤CountSqlParser的getSmartCountSql**
/**
     * 獲取智能的countSql
     *
     * @param sql
     * @param name 列名,默認 0
     * @return
     */
    public String getSmartCountSql(String sql, String name) {
        //校驗是否支持該sql
        isSupportedSql(sql);
        //解析SQL
        Statement stmt = null;
        //特殊sql不需要去掉order by時,使用註釋前綴
        if (sql.indexOf(KEEP_ORDERBY) >= 0) {
            return getSimpleCountSql(sql);
        }
        try {
            stmt = CCJSqlParserUtil.parse(sql);
        } catch (Throwable e) {
            //無法解析的用一般方法返回count語句
            return getSimpleCountSql(sql);
        }
        Select select = (Select) stmt;
        SelectBody selectBody = select.getSelectBody();
        try {
            //處理body-去order by
            processSelectBody(selectBody);
        } catch (Exception e) {
            //當 sql 包含 group by 時,不去除 order by
            return getSimpleCountSql(sql);
        }
        //處理with-去order by
        processWithItemsList(select.getWithItemsList());
        //處理爲count查詢
        sqlToCount(select, name);
        String result = select.toString();
        return result;
    }

繼續往下追蹤CCJSqlParserUtil的parse方法時出現sql轉換錯誤

public static Statement parse(String sql) throws JSQLParserException {
		CCJSqlParser parser = new CCJSqlParser(new StringReader(sql));
		try {
			return parser.Statement();
		} catch (Exception ex) {
			throw new JSQLParserException(ex);
		} 
	}

拋出的JSQLParserException異常:
net.sf.jsqlparser.parser.ParseException: Encountered " “(” "( “” at line 1, column 856.
Was expecting one of:
“AS” …
“DO” …
“ANY” …
“KEY” …
“PERCENT” …
“INTO” …
“FROM” …
“OPEN” …
“WHERE” …
“FOR” …
“XML” …
“UNION” …
“GROUP” …
“ORDER” …
“VALUE” …
“HAVING” …
“VALUES” …
“REPLACE” …
“TRUNCATE” …
“INTERSECT” …
“CAST” …
“EXCEPT” …
“MINUS” …
“OVER” …
“PARTITION” …
“EXTRACT” …
“MATERIALIZED” …
“START” …
“CONNECT” …
“PRIOR” …
“SIBLINGS” …
“COLUMN” …
“NULLS” …
“FIRST” …
“LAST” …
“ROWS” …
“RANGE” …
“FOLLOWING” …
“ROW” …
“SEPARATOR” …
“CASCADE” …
“NO” …
“ACTION” …
<S_IDENTIFIER> …
<S_QUOTED_IDENTIFIER> …
通過分析SQL語句定位到是因爲使用了IIF函數解析時遇到特殊字符轉換失敗導致的,而IIF函數是SQLServer 2012版本之後的發佈的函數,目前採用的5.0.1版本暫不支持該函數,但是需要注意的是並不是所有函數都不支持,比如支持FORMAT、CONVERT、ISNULL等函數

那麼我們通過錯誤日誌分析到了問題的原因了,那怎麼解決呢?

**處理方案如下:**
第一、升級pagehelper jar包的版本到最新的5.1.11
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.11</version>
</dependency>
第二、保留現有pagehelper jar包的版本不變,刪除IIF函數引用,改爲case when做邏輯判斷
select a.* from (SELECT b.id,b.cid,b.customerId,c.opportunityId,b.customerName,b.detailAddress,b.stageId,b.visitDate,b.isIntention,b.productIds,b.creatorId,b.creatorName,b.contactsId,b.contactsName,b.visitItems,b.visitType,b.accompanyVisitorIds,b.createTime,b.modifyTime,c.longitude as cusLongitude,c.latitude as cusLatitude,2 as customerType,c.salesId from tCustomerVisitPlan b inner join tCustomer c on b.customerId = c.id WHERE b.cid=? and b.creatorId=? and b.visitDate=? AND b.isDel=0 UNION ALL SELECT b.id,b.cid,c.customerId,b.opportunityId,b.opportunityName as customerName,b.detailAddress,b.stageId,b.visitDate,1 as isIntention,b.productIds,b.creatorId,b.creatorName,b.contactsId,b.contactsName,b.visitItems,b.visitType,b.accompanyVisitorIds,b.createTime,b.modifyTime,c.longitude as cusLongitude,c.latitude as cusLatitude,1 as customerType,(case when c.customerId is null or c.customerId=0  then c.salesId else d.salesId end) AS salesId from tOpportunityVisitPlan b inner join tOpportunity c on b.opportunityId = c.id left join tCustomer d on c.customerId = d.id WHERE b.cid=? and b.creatorId=? and b.visitDate=? AND b.isDel=0) as a order by a.modifyTime desc,a.createTime desc
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章