iBATIS获取真正执行SQL

最近项目上有一需求,获取ibatis执行的sql,注意是可以贴到客户端直接执行的SQL,搜索引擎加API查看,找到如下方式(废话不多说,直接上代码):

import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import com.ibatis.sqlmap.engine.mapping.parameter.ParameterMap;
import com.ibatis.sqlmap.engine.mapping.parameter.ParameterMapping;
import com.ibatis.sqlmap.engine.mapping.sql.Sql;
import com.ibatis.sqlmap.engine.mapping.statement.MappedStatement;
import com.ibatis.sqlmap.engine.scope.SessionScope;
import com.ibatis.sqlmap.engine.scope.StatementScope;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
 
public class IBatisUtil {
    private static Log log = LogFactory.getLog(IBatisUtil.class);
    /**
     * 获取当前执行的sql
     * @param template
     * @param sqlName
     * @param param
     * @return
     */
    public static String getCurrentSql(SqlMapClientTemplate template, String sqlName, Object param){
        String sql = "";
        SqlMapClientImpl sqlmap = (SqlMapClientImpl)template.getSqlMapClient();
        MappedStatement stmt = sqlmap.getMappedStatement(sqlName);
        Sql stmtSql = stmt.getSql();
        SessionScope sessionScope = new SessionScope();
        StatementScope statementScope = new StatementScope(sessionScope);
        statementScope.setStatement(stmt);
        sql = stmtSql.getSql(statementScope, param);
        ParameterMap parameterMap = stmtSql.getParameterMap(statementScope, param);
        Object[] objs = null;
        if(parameterMap != null){
            objs = parameterMap.getParameterObjectValues(statementScope, param);
        }
        ParameterMapping[] parameterMappings = parameterMap.getParameterMappings();
        log.debug("[ignite]parameterMappings length=" + parameterMappings.length);
        for (int i = 0; i < parameterMappings.length; i++) {
            log.debug("[ignite]parameterName=" + parameterMappings[i].getPropertyName() + "; parameterValue=" + objs[i]);
        }
        return getPreparedSql(sql, objs);
    }
    public static String getPreparedSql(String sql, Object[] params){
        //1 如果没有参数,说明是不是动态SQL语句
        int paramNum = 0;
        if (null != params) paramNum = params.length;
        if (1 > paramNum) return sql;
        //2 如果有参数,则是动态SQL语句
        StringBuffer stringBuffer = new StringBuffer();
        String[] subsql = sql.split("\\?");
        for (int i = 0; i < paramNum; i++) {
            if(params[i] instanceof Integer){
                stringBuffer.append(subsql[i]).append(" ").append(params[i]).append(" ");
            }else{
                stringBuffer.append(subsql[i]).append(" '").append(params[i]).append("' ");
            }
        }
        if (subsql.length > params.length) {
            stringBuffer.append(subsql[subsql.length - 1]);
        }
        return stringBuffer.toString();
    }
}

你可能感兴趣的:(iBATIS获取真正执行SQL)