如何从ibatis中获取SQL


以下是在网上搜到的办法:


运行期从ibatis配置文件中获取sql的两种方法
运行期从ibatis配置文件中获取sql
1.通过SqlMapClientDaoSupport,SqlMapClientImpl,MappedStatement,Sql,RequestScope等ibatis提供的类

public List getUserList(UserInfo userInfo) {
   String sql = null;
   SqlMapClientImpl sqlmap = (SqlMapClientImpl) this.getSqlMapClient();
   MappedStatement stmt = sqlmap.getMappedStatement("getUserInfoList");
   Sql stmtSql = stmt.getSql();
  
   RequestScope requestScope = new RequestScope();
   requestScope.setStatement(stmt);
   sql = stmtSql.getSql(requestScope, userInfo);
   System.out.println(sql);
   return null; 
}



注:这个方法我是写在dao中的,该dao extends SqlMapClientDaoSupport,所以上述就可以直接this调用getSqlMapClient()方法,


2.通过SqlMapExecutorDelegate,MappedStatement,Sql,RequestScope等ibatis提供的类
public List getUserList(UserInfo userInfo) {
   SqlMapExecutorDelegate delegate=((ExtendedSqlMapClient)
    (getSqlMapClientTemplate().getSqlMapClient())).getDelegate();     
   
   MappedStatement ms = delegate.getMappedStatement("getUserInfoList");   
   Sql sql=ms.getSql(); 
   RequestScope requestScope = new RequestScope();
   requestScope.setStatement(ms);
   String sqlStr = sql.getSql(requestScope,userInfo); 
   System.out.println(sqlStr); 
}




注:这两个例子中用到的类都是ibatis官方jar文件中的,快速导入即可,"getUserInfoList"为ibatis的xml文件中配置的id,getSql(,)
中第二个参数就是要传递的参数对象。

上述写法完全可以再简化,上述只是简单介绍,可供参考.......


参考:http://hi.baidu.com/iduany/item/254166ffaef7a3e81a111f71



但是以上方法有点问题,ibatis参数有$和#之分,当#的时候,获取出来的SQL是含有?号的。


我想ibatis一定也是最后使用的是JDBC的一种实现,所以就debug了一下源代码。

看了一下,总结了一下,可以这样实现:


package com.seven.dbTools.ibatis;

import java.util.HashMap;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

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

public class IbatisUtil extends SqlMapClientDaoSupport {

	/**
	 * get sql from ibatis :从ibatis中获取sql已经动态参数
	 * @param sqlid : sqlMap中的id
	 * @param parameterMap : 参数map
	 * @return
	 */
	public Map getSqlAndParametersFromIbatis(String sqlid,
			Map parameterMap) {
		String sql = null;
		SqlMapClientImpl sqlmap = (SqlMapClientImpl) this.getSqlMapClient();
		MappedStatement stmt = sqlmap.getMappedStatement(sqlid);
		Sql stmtSql = stmt.getSql();
		RequestScope requestScope = new RequestScope();
		requestScope.setStatement(stmt);
		ParameterMap dynamicParameterMap = stmtSql.getParameterMap(
				requestScope, parameterMap);
		Object[] values = null;
		if (dynamicParameterMap != null) {
			values = dynamicParameterMap.getParameterObjectValues(requestScope,
					parameterMap);
		}
		sql = stmtSql.getSql(requestScope, parameterMap);
		Map sqlMap = new HashMap();
		sqlMap.put(sql, values);
		return sqlMap;
	}

}

以上代码得到SQL和动态的参数。


你可能感兴趣的:(ibatis,JDBC)