Java获取Mybatis动态生成的sql

前提:已经编写好相应的接口个xml文件

public	void exportExcel_bw() throws Exception {
        //封装sql需要查询的sql的条件
        Map<String, Object> paramMap = new HashMap();
        paramMap.put("parentName", "权限管理");
        paramMap.put("pageBegin", 0);
        paramMap.put("pageSize", 20);
        //获取执行sql
        Configuration con = sqlSessionFactory.getConfiguration();
        //传xml文件中的 需要执行的id编号  如下图说明
        MappedStatement s = con.getMappedStatement(com.sgd.eic.nxdb.yhqd.dao.YhqdSuspectEleStealDao.selectSuspectUserEleStealStat);
        BoundSql bSql = s.getBoundSql(paramMap);
        //获取到sql中封装的参数的数量
        List<ParameterMapping> paramValues = bSql.getParameterMappings();
        String sql=getExecuteSql(bSql.getSql(),paramValues,paramMap);
        //创建连接
        SqlSession session = sqlSessionFactory.openSession();
        Statement cs = session.getConnection().createStatement();
        ResultSet set = cs.executeQuery(sql);//执行查询
        System.out.println(sql);
    }

/**
     * 生成可执行sql
     * @param sql 获取的sql
     * @param paramValues 动态参key
     * @param map 动态参valur
     * @return
     */
    private String getExecuteSql(String sql, List<ParameterMapping> paramValues,Map map) {
        while(sql.indexOf("?") != -1 && paramValues.size() > 0) {
            String paramName = paramValues.get(0).getProperty();
            String paramValue = map.get(paramName).toString();
            String value = "";
            if (paramValue instanceof String) {
                value = "'" + paramValue + "'";
            }
            sql = sql.replaceFirst("\\?", value);
            paramValues.remove(0);
        }
        return sql;
    }

 

参考:http://www.360doc.com/content/17/0415/16/21706453_645828496.shtml

posted @ 2019-11-20 18:01  yinder  阅读(2245)  评论(0编辑  收藏  举报