论mybatis 如何解析动态sql 例如<if> 标签

  • Post author:
  • Post category:其他



    /**
     * 处理SQL语句
     *
     * @param oldSql select * from s_a a
     *               where <if test="name != null && name != ''">
     *               a.name = #name#
     *               </if>
     * @return
     */
    public String dealSqlIf(String oldSql, JSONObject requestParams) throws DocumentException, OgnlException {
        StringBuffer newSql = new StringBuffer();
        String tmpSql = "";
        Boolean conditionResult = false;
        // 未包含 条件语句
        if (!oldSql.contains("<if")) {
            return oldSql;
        }
		// 基于< /if> 切割
        String[] oSqls = oldSql.split("</if>");
        for (String oSql : oSqls) {
            logger.debug("处理if 节点,当前处理的oSql=" + oSql + "总的oSqls = " + oSqls);
	    // 此处分2截  最后一 截 走这里
            if (StringUtil.isEmpty(oSql) || !oSql.contains("<if")) {
                newSql.append(oSql);
                continue;
            }
            // 第一截会进入
                if (!oSql.startsWith("<if")) {
                newSql.append(oSql.substring(0, oSql.indexOf("<if")));
            }

            tmpSql = oSql.substring(oSql.indexOf("<if")) + "</if>";
//  将If 条件转成 root节点 此处需要用dom4j 的jar
            Element root = 	DocumentHelper.parseText(tmpSql).getRootElement();

            String condition = root.attribute("test").getValue();

// 着2端代码可以调试看结果 我也说不来
            Object condObj = Ognl.parseExpression(condition);

            Object value = Ognl.getValue(condObj, requestParams);

            if (value instanceof Boolean) {
                conditionResult = (Boolean) value;
            } else {
     throw new RuntimeException()
            }

            if (conditionResult) {
                newSql.append(root.getText());
            }


        }


        return newSql.toString().replace("&gt;", ">").replace("&lt;", "<");

    }
     String utils =" select a.user_id userId,a.name userName,a.password userPwd \n" +
                "from u_user a where a.name = #userCode# \n" +
                "<if test=\"pwd != null and pwd != ''\">\n" +
                "and a.password = #pwd#\n" +
                "</if>\n" +
                "and a.status_cd = '0'";

        JSONObject xxx = new JSONObject();
        xxx.put("pwd","1");

        String s1 = dealSqlIf(utils, xxx);
        System.out.println(s1);
        可以自己测试结果



版权声明:本文为weixin_45542377原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。