读书人

Ibatis 三 获取运行期sql和参数

发布时间: 2012-10-29 10:03:53 作者: rapoo

Ibatis 3 获取运行期sql和参数
跟踪ibatis 3 代码,找到获取运行期的动态sql和参数

在其它框架的dao实现,如hibernate或jdbc,可以把sql(hql)集中交给ibatis处理。基于动态sql,使得你的sql(hql)不再在代码中使用String拼接,且获得ibatis动态支持.


用于保存结果



获取
/** *  * @param id xml 中sql的id ,如 <select id="XXX">中的"XXX" * @param parameterObject 传给这条sql的参数 * @return */public IbatisSql getIbatisSql(String id, Object parameterObject) {IbatisSql ibatisSql = new IbatisSql();SqlSessionFactory sqlSessionFactory = ...//参考官方例子MappedStatement ms = sqlSessionFactory.getConfiguration().getMappedStatement(id);BoundSql boundSql = ms.getBoundSql(parameterObject);List<ResultMap> ResultMaps=ms.getResultMaps();if(ResultMaps!=null&&ResultMaps.size()>0){ResultMap ResultMap = ms.getResultMaps().get(0);ibatisSql.setResultClass(ResultMap.getType());}ibatisSql.setSql(boundSql.getSql());List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();    if (parameterMappings != null) {Object[] parameterArray = new Object[parameterMappings.size()];        MetaObject metaObject = parameterObject == null ? null : MetaObject.forObject(parameterObject);        for (int i = 0; i < parameterMappings.size(); i++) {          ParameterMapping parameterMapping = parameterMappings.get(i);          if (parameterMapping.getMode() != ParameterMode.OUT) {            Object value;            String propertyName = parameterMapping.getProperty();            PropertyTokenizer prop = new PropertyTokenizer(propertyName);            if (parameterObject == null) {              value = null;            } else if (ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass())) {              value = parameterObject;            } else if (boundSql.hasAdditionalParameter(propertyName)) {              value = boundSql.getAdditionalParameter(propertyName);            } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)                && boundSql.hasAdditionalParameter(prop.getName())) {              value = boundSql.getAdditionalParameter(prop.getName());              if (value != null) {                value = MetaObject.forObject(value).getValue(propertyName.substring(prop.getName().length()));              }            } else {              value = metaObject == null ? null : metaObject.getValue(propertyName);            }            parameterArray[i] = value;          }        }ibatisSql.setParameters(parameterArray);    }return ibatisSql;}

读书人网 >SQL Server

热点推荐