druid解析的sql

public void search(String sql, Map conditions, String operator) {
        List> result = new ArrayList<>();
        // SQLParserUtils.createSQLStatementParser可以将sql装载到Parser里面
        SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcUtils.MYSQL);
        // parseStatementList的返回值SQLStatement本身就是druid里面的语法树对象
        List stmtList = parser.parseStatementList();
        SQLStatement stmt = stmtList.get(0);
        if (stmt instanceof SQLSelectStatement) {
            // convert conditions to 'and' statement
            StringBuffer constraintsBuffer = new StringBuffer();
            Iterator> entryIterator = conditions.entrySet().iterator();
            if (entryIterator.hasNext()) {
                Map.Entry entry = entryIterator.next();
                constraintsBuffer.append(entry.getKey()).append(" = ").append(entry.getValue());
            }
            while (entryIterator.hasNext()) {
                Map.Entry entry = entryIterator.next();
                constraintsBuffer.append(" "+operator+" ").append(entry.getKey()).append(" = ").append(entry.getValue());
            }
            SQLExprParser constraintsParser = SQLParserUtils.createExprParser(constraintsBuffer.toString(), JdbcUtils.MYSQL);
            SQLExpr constraintsExpr = constraintsParser.expr();
            SQLSelectStatement selectStmt = (SQLSelectStatement) stmt;
            // 拿到SQLSelect 通过在这里打断点看对象我们可以看出这是一个树的结构
            SQLSelect sqlselect = selectStmt.getSelect();
            SQLSelectQueryBlock query = (SQLSelectQueryBlock) sqlselect.getQuery();
            SQLExpr whereExpr = query.getWhere();
            // 修改where表达式
            if (whereExpr == null) {
                query.setWhere(constraintsExpr);
            } else {
                SQLBinaryOperator sqlBinaryOperator = null;
                for (SQLBinaryOperator value : SQLBinaryOperator.values()) {
                    if (value.getName().equalsIgnoreCase(operator)){
                        sqlBinaryOperator = value;
                        break;
                    }
                }
                SQLBinaryOpExpr newWhereExpr = new SQLBinaryOpExpr(whereExpr, sqlBinaryOperator, constraintsExpr);
                query.setWhere(newWhereExpr);
            }
            sqlselect.setQuery(query);
            sql = sqlselect.toString();
            System.out.println(sql);
        }

 

你可能感兴趣的:(springMVC)