{"record":{"id":"fc46bafeeb8d4561","repo":"pagehelper-org/Mybatis-PageHelper","slug":"failed-to-handle-sorting-e-downgraded-to-a-di","errorCode":null,"errorMessage":"Failed to handle sorting: ${e}, downgraded to a direct splice of the order by parameter","messagePattern":"Failed to handle sorting: (.+?), downgraded to a direct splice of the order by parameter","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"src/main/java/com/github/pagehelper/parser/defaults/DefaultOrderBySqlParser.java","lineNumber":69,"sourceCode":"     * @return\n     */\n    @Override\n    public String converToOrderBySql(String sql, String orderBy) {\n        //解析SQL\n        Statement stmt = null;\n        try {\n            stmt = SqlParserUtil.parse(sql);\n            Select select = (Select) stmt;\n            //处理body-去最外层order by\n            List<OrderByElement> orderByElements = extraOrderBy(select);\n            String defaultOrderBy = PlainSelect.orderByToString(orderByElements);\n            if (defaultOrderBy.indexOf('?') != -1) {\n                throw new PageException(\"The order by in the original SQL[\" + sql + \"] contains parameters, so it cannot be modified using the OrderBy plugin!\");\n            }\n            //新的sql\n            sql = select.toString();\n        } catch (Throwable e) {\n            log.warn(\"Failed to handle sorting: \" + e + \", downgraded to a direct splice of the order by parameter\");\n        }\n        return sql + \" order by \" + orderBy;\n    }\n\n    /**\n     * extra order by and set default orderby to null\n     *\n     * @param select\n     */\n    public static List<OrderByElement> extraOrderBy(Select select) {\n        if (select != null) {\n            if (select instanceof PlainSelect || select instanceof SetOperationList) {\n                List<OrderByElement> orderByElements = select.getOrderByElements();\n                select.setOrderByElements(null);\n                return orderByElements;\n            } else if (select instanceof ParenthesedSelect) {\n                extraOrderBy(((ParenthesedSelect) select).getSelect());\n            }","sourceCodeStart":51,"sourceCodeEnd":87,"githubUrl":"https://github.com/pagehelper-org/Mybatis-PageHelper/blob/c692616c5bc95b41aa779b502f991825c8e5acbc/src/main/java/com/github/pagehelper/parser/defaults/DefaultOrderBySqlParser.java#L51-L87","documentation":"DefaultOrderBySqlParser attempted to rewrite the SQL to inject the orderBy clause using JSqlParser, but parsing/modification failed with a Throwable. This is not fatal: the parser logs a warning and falls back to naively appending ' order by <orderBy>' to the original SQL string. The message includes the underlying exception.","triggerScenarios":"Original SQL that JSqlParser cannot parse (dialect-specific syntax, comments, CTEs, UNION, stored-procedure calls like CALL/EXEC); the original SQL already contains an ORDER BY with a '?' placeholder parameter; complex SELECT with DB-specific functions unsupported by the bundled JSqlParser version.","commonSituations":"Using PageHelper's orderBy support on legacy hand-written SQL with vendor syntax; passing OrderBy sql to queries with bind parameters in ORDER BY; JSqlParser version too old for the SQL grammar in use (upgrade fixes many cases).","solutions":["Simplify or rewrite the SQL so JSqlParser can parse it (remove vendor-specific constructs or split complex UNION/CTE queries)","Upgrade pagehelper (and its bundled JSqlParser) to a newer version supporting your SQL grammar","Ensure the original SQL has no ORDER BY clause when using OrderByHelper, and definitely no '?' parameters inside ORDER BY","Verify the fallback result manually: since 'order by' is string-appended, check the generated SQL and add the ordering in the SQL itself if the fallback is wrong"],"exampleFix":"// before (unparseable by JSqlParser)\norderBy(\"id desc\") over \"SELECT ... WHERE name = {fn CONCAT(a,b)}\"\n// after — order in SQL directly\nString sql = \"SELECT ... ORDER BY id DESC\"; // skip OrderByHelper\nPageHelper.orderBy(\"id desc\"); // only for JSqlParser-compatible SQL","handlingStrategy":"fallback","validationCode":"// pre-check: ORDER BY with a placeholder cannot be rewritten\nif (sql.matches(\"(?is).*order\\\\s+by[^)]*\\\\?.*\")) {\n    log.warn(\"skip OrderByHelper: SQL has parameterized ORDER BY\");\n}\n// ideally: verify the SQL parses with the same JSqlParser version\nCCJSqlParserUtil.parse(sql); // throws if unsupported -> handle before paging","typeGuard":null,"tryCatchPattern":"try {\n    PageHelper.orderBy(\"id desc\");\n    list = mapper.select();\n} catch (Exception e) {\n    log.warn(\"orderBy plugin failed, ordering manually\", e);\n    list.sort(Comparator.comparing(Entity::getId).reversed());\n}","preventionTips":["Keep pagehelper and JSqlParser versions current to widen supported SQL grammar","Prefer explicit ORDER BY in the SQL over runtime orderBy injection for complex queries","Review warnings from DefaultOrderBySqlParser — fallback string concatenation may produce wrong or invalid SQL","Test all production SQL statements against the parser before enabling OrderByHelper globally"],"tags":["sql-parsing","order-by","fallback","jsqlparser","pagehelper"],"backgroundTag":"sql-query-failed","analyzedSha":"c692616c5bc95b41aa779b502f991825c8e5acbc","analyzedAt":"2026-09-08T03:50:49.192Z","contentChangedAt":"2026-09-08T03:50:49.192Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}