Java Code Examples for org.apache.ibatis.mapping.BoundSql#getParameterMappings()

The following examples show how to use org.apache.ibatis.mapping.BoundSql#getParameterMappings() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MySqlDialect.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
    paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
    paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
    //处理pageKey
    pageKey.update(page.getStartRow());
    pageKey.update(page.getPageSize());
    //处理参数配置
    if (boundSql.getParameterMappings() != null) {
        List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
        if (page.getStartRow() == 0) {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        } else {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class).build());
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        }
        MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
        metaObject.setValue("parameterMappings", newParameterMappings);
    }
    return paramMap;
}
 
Example 2
Source File: PageInterceptor.java    From Zebra with Apache License 2.0 6 votes vote down vote up
private Object queryLimit(Invocation invocation, Object[] args, MappedStatement ms, BoundSql boundSql, RowBounds rb)
		throws InvocationTargetException, IllegalAccessException {
	String limitSql = dialect.getLimitSql(boundSql.getSql(), rb.getOffset(), rb.getLimit());
	BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), limitSql, boundSql.getParameterMappings(),
			boundSql.getParameterObject());
	MetaObject mo = (MetaObject) ReflectionUtils.getFieldValue(boundSql, "metaParameters");
	ReflectionUtils.setFieldValue(newBoundSql, "metaParameters", mo);

	args[0] = buildMappedStatement(ms, new SqlSourceWrapper(newBoundSql), ms.getId() + "_LIMIT",
			ms.getResultMaps());
	args[2] = new RowBounds();
	args[3] = null;

	try {
		DaoContextHolder.setSqlName(buildDaoName(ms.getId()) + "_LIMIT");
		return invocation.proceed();
	} finally {
		DaoContextHolder.clearSqlName();
	}
}
 
Example 3
Source File: MyBatisUtils.java    From platform with Apache License 2.0 6 votes vote down vote up
/**
 * 复制BoundSql
 *
 * @param mappedStatement   ${@link MappedStatement}
 * @param boundSql          ${@link BoundSql}
 * @param sql               SQL
 * @param parameterMappings 参数映射
 * @param parameter         参数
 * @return {@link BoundSql}
 */
public static BoundSql copyFromBoundSql(MappedStatement mappedStatement,
                                        BoundSql boundSql,
                                        String sql,
                                        Object parameter) {

    List<ParameterMapping> parameterMappings = new ArrayList<>(boundSql.getParameterMappings());

    BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), sql, parameterMappings, parameter);

    for (ParameterMapping mapping : boundSql.getParameterMappings()) {
        String prop = mapping.getProperty();
        if (boundSql.hasAdditionalParameter(prop)) {
            newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
        }
    }
    return newBoundSql;
}
 
Example 4
Source File: HerdDBDialect.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
    paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
    paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
    pageKey.update(page.getStartRow());
    pageKey.update(page.getPageSize());
    if (boundSql.getParameterMappings() != null) {
        List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
        if (page.getStartRow() == 0) {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        } else {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class).build());
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        }
        MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
        metaObject.setValue("parameterMappings", newParameterMappings);
    }
    return paramMap;
}
 
Example 5
Source File: AddDateInterceptor.java    From dynamic-add-date with MIT License 6 votes vote down vote up
/**
 * 解决原始sql语句已包含自动添加的列导致参数数量映射异常的问题
 *
 * @param boundSql
 */
private void handleParameterMapping(BoundSql boundSql) {
    List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
    Iterator<ParameterMapping> it = parameterMappingList.iterator();
    String camelCaseCreateDateProperty = StringUtil.camelCase(createDateColumnName);
    String camelCaseUpdateDateProperty = StringUtil.camelCase(updateDateColumnName);
    while (it.hasNext()) {
        ParameterMapping pm = it.next();
        if (pm.getProperty().equals(camelCaseCreateDateProperty)) {
            log.debug("原始Sql语句已包含自动添加的列: {}", createDateColumnName);
            it.remove();
        }
        if (pm.getProperty().equals(camelCaseUpdateDateProperty)) {
            log.debug("原始Sql语句已包含自动添加的列: {}", updateDateColumnName);
            it.remove();
        }
    }
}
 
Example 6
Source File: BaseExecutor.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql) {
  //处理存储过程的OUT参数
  if (ms.getStatementType() == StatementType.CALLABLE) {
    final Object cachedParameter = localOutputParameterCache.getObject(key);
    if (cachedParameter != null && parameter != null) {
      final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter);
      final MetaObject metaParameter = configuration.newMetaObject(parameter);
      for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
        if (parameterMapping.getMode() != ParameterMode.IN) {
          final String parameterName = parameterMapping.getProperty();
          final Object cachedValue = metaCachedParameter.getValue(parameterName);
          metaParameter.setValue(parameterName, cachedValue);
        }
      }
    }
  }
}
 
Example 7
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
private void cpyAndAppendParameters(MappedStatement ms, Pagination pg, BoundSql boundSql, BoundSql newBoundSql){
	// cpy old parameters
	for (ParameterMapping mapping : newBoundSql.getParameterMappings()) {
		String prop = mapping.getProperty();
		if (boundSql.hasAdditionalParameter(prop)) {
			newBoundSql.setAdditionalParameter(prop,
					boundSql.getAdditionalParameter(prop));
		}
	}
	
	// append pagination parameters
	Configuration cf = ms.getConfiguration();
	TypeHandler<?> type =  cf.getTypeHandlerRegistry().getTypeHandler(Integer.class);
	ParameterMapping offsetMapping = new ParameterMapping.Builder(cf,
			OFFSET_PARAMETER, type).build();
	ParameterMapping limitMapping = new ParameterMapping.Builder(cf,
			LIMIT_PARAMETER, type).build();
	
	ParameterMapping[] mappings = new ParameterMapping[]{offsetMapping, limitMapping}; 
	for (Order order : dialect.order()) {
		newBoundSql.getParameterMappings().add(mappings[order.ordinal()]);
	}
	
	newBoundSql.setAdditionalParameter(OFFSET_PARAMETER, pg.getOffset());
	
	// 如果是Oracle,第二个参数需要设置起始位置加Limit得到结束位置
	// 与MySql是不一样
	if(DBMS.ORACLE.name().equals(dbms)){
		newBoundSql.setAdditionalParameter(LIMIT_PARAMETER, pg.getOffset() + pg.getLimit());
	}else{
		newBoundSql.setAdditionalParameter(LIMIT_PARAMETER, pg.getLimit());
	}
}
 
Example 8
Source File: SQLHelper.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
     * 查询总纪录数
     * @param sql             SQL语句
     * @param connection      数据库连接
     * @param mappedStatement mapped
     * @param parameterObject 参数
     * @param boundSql        boundSql
     * @return 总记录数
     * @throws SQLException sql查询错误
     */
    public static int getCount(final String sql, final Connection connection,
    							final MappedStatement mappedStatement, final Object parameterObject,
    							final BoundSql boundSql, Log log) throws SQLException {
        final String countSql = "select count(1) from (" + sql + ") tmp_count";
//        final String countSql = "select count(1) " + removeSelect(removeOrders(sql));
        Connection conn = connection;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
        	if (log.isDebugEnabled()) {
                log.debug("COUNT SQL: " + StringUtils.replaceEach(countSql, new String[]{"\n", "\t"}, new String[]{" ", " "}));
            }
        	if (conn == null){
        		conn = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection();
            }
        	ps = conn.prepareStatement(countSql);
            BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,
                    boundSql.getParameterMappings(), parameterObject);
            SQLHelper.setParameters(ps, mappedStatement, countBS, parameterObject);
            rs = ps.executeQuery();
            int count = 0;
            if (rs.next()) {
                count = rs.getInt(1);
            }
            return count;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
            	ps.close();
            }
            if (conn != null) {
            	conn.close();
            }
        }
    }
 
Example 9
Source File: SQLHelper.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
 *
 * @param ps              表示预编译的 SQL 语句的对象。
 * @param mappedStatement MappedStatement
 * @param boundSql        SQL
 * @param parameterObject 参数对象
 * @throws java.sql.SQLException 数据库异常
 */
@SuppressWarnings("unchecked")
public static void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
        Configuration configuration = mappedStatement.getConfiguration();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        MetaObject metaObject = parameterObject == null ? null :
                configuration.newMetaObject(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 (typeHandlerRegistry.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 = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                    }
                } else {
                    value = metaObject == null ? null : metaObject.getValue(propertyName);
                }
                @SuppressWarnings("rawtypes")
	TypeHandler typeHandler = parameterMapping.getTypeHandler();
                if (typeHandler == null) {
                    throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                }
                typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
            }
        }
    }
}
 
Example 10
Source File: OffsetLimitInterceptor.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
private BoundSql copyFromBoundSql(MappedStatement ms, BoundSql boundSql,
		String sql, List<ParameterMapping> parameterMappings,Object parameter) {
	BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),sql, parameterMappings, parameter);
	for (ParameterMapping mapping : boundSql.getParameterMappings()) {
	    String prop = mapping.getProperty();
	    if (boundSql.hasAdditionalParameter(prop)) {
	        newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
	    }
	}
	return newBoundSql;
}
 
Example 11
Source File: BaseExecutor.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
  if (closed) {
    throw new ExecutorException("Executor was closed.");
  }
  CacheKey cacheKey = new CacheKey();
  //MyBatis 对于其 Key 的生成采取规则为:[mappedStementId + offset + limit + SQL + queryParams + environment]生成一个哈希码
  cacheKey.update(ms.getId());
  cacheKey.update(Integer.valueOf(rowBounds.getOffset()));
  cacheKey.update(Integer.valueOf(rowBounds.getLimit()));
  cacheKey.update(boundSql.getSql());
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
  // mimic DefaultParameterHandler logic
  //模仿DefaultParameterHandler的逻辑,不再重复,请参考DefaultParameterHandler
  for (int i = 0; i < parameterMappings.size(); i++) {
    ParameterMapping parameterMapping = parameterMappings.get(i);
    if (parameterMapping.getMode() != ParameterMode.OUT) {
      Object value;
      String propertyName = parameterMapping.getProperty();
      if (boundSql.hasAdditionalParameter(propertyName)) {
        value = boundSql.getAdditionalParameter(propertyName);
      } else if (parameterObject == null) {
        value = null;
      } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
        value = parameterObject;
      } else {
        MetaObject metaObject = configuration.newMetaObject(parameterObject);
        value = metaObject.getValue(propertyName);
      }
      cacheKey.update(value);
    }
  }
  if (configuration.getEnvironment() != null) {
    // issue #176
    cacheKey.update(configuration.getEnvironment().getId());
  }
  return cacheKey;
}
 
Example 12
Source File: SqlHelper.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 通过命名空间方式获取sql
 * @param session
 * @param namespace
 * @param params
 * @return
 */
public static String getNamespaceSql(SqlSession session, String namespace, Object params) {
    Configuration configuration = session.getConfiguration();
    MappedStatement mappedStatement = configuration.getMappedStatement(namespace);
    TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
    BoundSql boundSql = mappedStatement.getBoundSql(params);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    String sql = boundSql.getSql();
    if (parameterMappings != null) {
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (params == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(params.getClass())) {
                    value = params;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(params);
                    value = metaObject.getValue(propertyName);
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();
                if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
                sql = replaceParameter(sql, value, jdbcType, parameterMapping.getJavaType());
            }
        }
    }
    return sql;
}
 
Example 13
Source File: PagePluging.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
void processIntercept(final Object[] queryArgs) {
	MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
	Object parameter = queryArgs[PARAMETER_INDEX];
	final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];
	int offset = rowBounds.getOffset();
	int limit = rowBounds.getLimit();
	if (dialect.supportsLimit() && (offset != RowBounds.NO_ROW_OFFSET || limit != RowBounds.NO_ROW_LIMIT)) {
		BoundSql boundSql = ms.getBoundSql(parameter);
		String sql = boundSql.getSql().trim();
		if (dialect.supportsLimitOffset()) {
			sql = dialect.getLimitString(sql, offset, limit);
			offset = RowBounds.NO_ROW_OFFSET;
		} else {
			sql = dialect.getLimitString(sql, 0, limit);
		}
		limit = RowBounds.NO_ROW_LIMIT;
		queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit);
		BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(),
				boundSql.getParameterObject());
		for (ParameterMapping mapping : boundSql.getParameterMappings()) {
			String prop = mapping.getProperty();
			if (boundSql.hasAdditionalParameter(prop)) {
				newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
			}
		}
		MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
		queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
	}
}
 
Example 14
Source File: DataPermissionInterceptor.java    From DataPermissionHelper with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    MappedStatement mappedStatement = (MappedStatement) args[0];
    Object parameter = args[1];
    //从当前线程获取需要进行数据权限控制的业务
    DataPermission dataPermission = DPHelper.getLocalDataPermissions();
    //判断有没有进行数据权限控制,是不是最高权限的管理员(这里指的是数据权限的白名单用户)
    if (dataPermission != null && dataPermission.getAdmin() == false) {
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        String sql = boundSql.getSql();
        //获得方法类型
        Select select = (Select) CCJSqlParserUtil.parse(sql);
        select.getSelectBody().accept(new SelectVisitorImpl());
        //判断当前sql是否被修改
        if (DPHelper.getChangeTable()) {
            //访问各个visitor
            //TODO:解析动态sql会失败
            BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), select.toString(), boundSql
                    .getParameterMappings(), parameter);
            String newMsId = mappedStatement.getId() + DATA_PERMISSION;
            MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql), newMsId);
            args[0] = newMs;
            DPHelper.clearChangeTable();
        }
    }
    return invocation.proceed();
}
 
Example 15
Source File: UpdateEnhancement.java    From mybatis-boost with MIT License 5 votes vote down vote up
private List<ParameterMapping> getParameterMappings(MetaObject metaObject, BoundSql boundSql, List<String> properties) {
    org.apache.ibatis.session.Configuration configuration = (org.apache.ibatis.session.Configuration)
            metaObject.getValue("delegate.configuration");
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    Object parameterObject = boundSql.getParameterObject();
    if (parameterObject instanceof Map) {
        for (int i = 1; i <= properties.size(); i++) {
            parameterMappings.add(i - 1,
                    new ParameterMapping.Builder(configuration, "param" + i, Object.class).build());
        }
    } else {
        parameterMappings.addAll(0, MyBatisUtils.getParameterMappings(configuration, properties));
    }
    return parameterMappings;
}
 
Example 16
Source File: CacheHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
/**
 * 按更新的查询条件更新缓存
 * @param executor
 * @param mt
 * @param mapperNameSpace
 * @param args
 */
private void removeCacheByUpdateConditon(Executor executor, MappedStatement mt,
                                         String mapperNameSpace, Object[] args) {
    try {
        Object parameterObject = args[1];
        EntityInfo entityInfo = MybatisMapperParser.getEntityInfoByMapper(mapperNameSpace);
        MappedStatement statement = getQueryIdsMappedStatementForUpdateCache(mt, entityInfo);
        if (statement == null) { return; }

        String querySql = statement.getSqlSource().getBoundSql(parameterObject).getSql();

        List<?> idsResult = null;
        if (PARSE_SQL_ERROR_DEFAULT.equals(querySql)) {
            BoundSql boundSql = mt.getBoundSql(parameterObject);
            querySql = "select " + entityInfo.getIdColumn() + " from "
                    + entityInfo.getTableName() + " WHERE "
                    + boundSql.getSql().split(WHERE_REGEX)[1];
            BoundSql queryBoundSql = new BoundSql(statement.getConfiguration(), querySql,
                    boundSql.getParameterMappings(), parameterObject);

            idsResult = executor.query(statement, parameterObject, RowBounds.DEFAULT,
                    new DefaultResultHandler(), null, queryBoundSql);
        } else {
            idsResult = executor.query(statement, parameterObject, RowBounds.DEFAULT, null);
        }

        if (idsResult != null && !idsResult.isEmpty()) {
            for (Object id : idsResult) {
                String cacheKey = entityInfo.getEntityClass().getSimpleName() + ID_CACHEKEY_JOIN
                        + id.toString();
                getCacheProvider().remove(cacheKey);
            }
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "_autocache_ update Method[{}] executed,remove ralate cache {}.id:[{}]",
                        mt.getId(), entityInfo.getEntityClass().getSimpleName(), idsResult);
            }
        }
    } catch (Exception e) {
        logger.error("_autocache_ update Method[{}] remove ralate cache error", e);
    }
}
 
Example 17
Source File: PagePlugin.java    From cms with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
	public Object intercept(Invocation invocation) throws Throwable {

		if (invocation.getTarget() instanceof RoutingStatementHandler) {
			RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
			BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler,
					"delegate");
			MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate,
					"mappedStatement");

			if (mappedStatement.getId().matches(pageSqlId)) {
				BoundSql boundSql = delegate.getBoundSql();
				Object parameterObject = boundSql.getParameterObject();
				if (parameterObject == null) {
					throw new NullPointerException("parameterObject is null.");
				} else {
					Connection connection = (Connection) invocation.getArgs()[0];
					String sql = boundSql.getSql();
					String countSql="select count(0) from (" + sql + ") tmp_count ";
					/*if ("mysql".equals(dialect)) {
						
					} else if ("oracle".equals(dialect)) {
					}*/
					PreparedStatement countStmt = connection.prepareStatement(countSql);
					BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,
							boundSql.getParameterMappings(), parameterObject);
					setParameters(countStmt, mappedStatement, countBS, parameterObject);
					ResultSet rs = countStmt.executeQuery();
					int count = 0;
					if (rs.next()) {
						count = rs.getInt(1);
					}
					rs.close();
					countStmt.close();

					Page page = null;
					if (parameterObject instanceof Page) {
						page = (Page) parameterObject;
						page.setTotalResult(count);
					} else if (parameterObject instanceof Map) {
						Map<String, Object> map = (Map<String, Object>) parameterObject;
						page = (Page) map.get("page");
						if (page == null)
							page = new Page();
						page.setTotalResult(count);
					} else {
						Field pageField = ReflectHelper.getFieldByFieldName(parameterObject, "page");
						if (pageField != null) {
							page = (Page) ReflectHelper.getValueByFieldName(parameterObject, "page");
							if (page == null)
								page = new Page();
							page.setTotalResult(count);
							ReflectHelper.setValueByFieldName(parameterObject, "page", page);
						} else {
							throw new NoSuchFieldException(parameterObject.getClass().getName());
						}
					}
					String pageSql = generatePageSql(sql, page);
					ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql);
				}
			}
		}

//		 Object result = invocation.proceed(); //执行请求方法,并将所得结果保存到result中
//		    if (result instanceof ArrayList) {
//		        ArrayList resultList = (ArrayList) result;
//		        for (int i = 0; i < resultList.size(); i++) {
//		            if (resultList.get(i) instanceof Map) {
//		                Map resultMap = (Map) resultList.get(i);
//		                resultMap.put("CERT_NO", "这个是加密结果"); //取出相应的字段进行加密
//		            }
//		        }
//		    }
		
		return invocation.proceed();
	}
 
Example 18
Source File: PagePlugin.java    From cms with Apache License 2.0 4 votes vote down vote up
/**
 * org.apache.ibatis.executor.parameter. DefaultParameterHandler
 * 
 * @param ps
 * @param mappedStatement
 * @param boundSql
 * @param parameterObject
 * @throws SQLException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,
		Object parameterObject) throws SQLException {
	ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
	List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
	if (parameterMappings != null) {
		Configuration configuration = mappedStatement.getConfiguration();
		TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
		MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(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 (typeHandlerRegistry.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 = configuration.newMetaObject(value)
								.getValue(propertyName.substring(prop.getName().length()));
					}
				} else {
					value = metaObject == null ? null : metaObject.getValue(propertyName);
				}
				TypeHandler typeHandler = parameterMapping.getTypeHandler();
				if (typeHandler == null) {
					throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName
							+ " of statement " + mappedStatement.getId());
				}
				typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
			}
		}
	}
}
 
Example 19
Source File: PaginationInterceptor.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
@Override
    public Object intercept(Invocation invocation) throws Throwable {

        final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        
//        //拦截需要分页的SQL
////        if (mappedStatement.getId().matches(_SQL_PATTERN)) {
//        if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) {
            Object parameter = invocation.getArgs()[1];
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            Object parameterObject = boundSql.getParameterObject();

            //获取分页参数对象
            Page<Object> page = null;
            if (parameterObject != null) {
                page = convertParameter(parameterObject, page);
            }

            //如果设置了分页对象,则进行分页
            if (page != null && page.getPageSize() != -1) {

            	if (StringUtils.isBlank(boundSql.getSql())){
                    return null;
                }
                String originalSql = boundSql.getSql().trim();
            	
                //得到总记录数
                page.setCount(SQLHelper.getCount(originalSql, null, mappedStatement, parameterObject, boundSql, log));

                //分页查询 本地化对象 修改数据库注意修改实现
                String pageSql = SQLHelper.generatePageSql(originalSql, page, DIALECT);
//                if (log.isDebugEnabled()) {
//                    log.debug("PAGE SQL:" + StringUtils.replace(pageSql, "\n", ""));
//                }
                invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
                BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
                MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));

                invocation.getArgs()[0] = newMs;
            }
//        }
        return invocation.proceed();
    }
 
Example 20
Source File: JdbcUtil.java    From easyooo-framework with Apache License 2.0 4 votes vote down vote up
private String buildStatmentSql(String sql, CountingExecutor ce){
	BoundSql boundSql = ce.getBoundSql();
	List<ParameterMapping> mappings = boundSql.getParameterMappings();
	if(mappings == null){
		return sql;
	}
	Object paramObject = boundSql.getParameterObject();
	TypeHandlerRegistry typeHandlerRegistry = ce.getMs().getConfiguration().getTypeHandlerRegistry();
	for (ParameterMapping pm : mappings) {
		String propertyName = pm.getProperty();
		Object value = null;
		if(paramObject != null){
			if(paramObject instanceof Map<?, ?>){
				value = ((Map<?,?>)paramObject).get(propertyName);
			} else if (typeHandlerRegistry.hasTypeHandler(paramObject.getClass())) {
	            value = paramObject;
	        }else{
				value = CglibUtil.getPropertyValue(paramObject, propertyName);
			}
		}
		if (value == null && boundSql.hasAdditionalParameter(propertyName)) {
			value = boundSql.getAdditionalParameter(propertyName);
		}
		
		String phString = "";
		if(value != null ){
			if(value instanceof String){
				phString ="'" + value.toString() +"'";
			}else if(value instanceof Date){
				phString ="'" +  SDF.format((Date)value) +"'";
			}else{
				phString = value.toString();
			}
		}else{
			logger.error(
					"property value may be losted. sql: {}, currentPropertyName: {}, boundSql: {}",
					sql, propertyName,JSON.toJSONString(boundSql));
			phString = null;
		}
		sql = sql.replaceFirst("\\?", phString);
	}
	return sql;
}