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

The following examples show how to use org.apache.ibatis.mapping.BoundSql#getParameterObject() . 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: SundialInterceptor.java    From Milkomeda with MIT License 6 votes vote down vote up
private void updateSql(String sql, Invocation invocation, MappedStatement ms, Object[] args, BoundSql boundSql) {
    BoundSql boundSqlNew = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    MappedStatement mappedStatement = copyFrom(ms, new BoundSqlSqlSource(boundSqlNew));
    // 替换映射的语句
    args[0] = mappedStatement;

    // 针对查询方式的参数替换
    if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
        Executor executor = (Executor) invocation.getTarget();
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        // 6个参数时(因为分页插件的原因导致问题,需要修改对应的类型值)
        if (args.length == 6) {
            args[4] = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            args[5] = boundSqlNew;
        }
    }
}
 
Example 2
Source File: PaginationInterceptor.java    From platform with Apache License 2.0 6 votes vote down vote up
/**
 * 查询总记录条数
 *
 * @param sql             SQL
 * @param mappedStatement {@link MappedStatement}
 * @param boundSql        {@link BoundSql}
 * @param connection      {@link Connection}
 */
protected long queryTotal(String sql, MappedStatement mappedStatement, BoundSql boundSql, Connection connection) {
    long total = 0;
    try (PreparedStatement statement = connection.prepareStatement(sql)) {
        DefaultParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql);
        parameterHandler.setParameters(statement);
        try (ResultSet resultSet = statement.executeQuery()) {
            if (resultSet.next()) {
                total = resultSet.getLong(1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return total;
}
 
Example 3
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 4
Source File: DataPermissionInterceptor.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    this.sqlParser(metaObject);
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    Object paramObj = boundSql.getParameterObject();
    // 数据权限只针对查询语句
    if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType()) {
        DataPermission dataPermission = getDataPermission(mappedStatement);
        if (shouldFilter(mappedStatement, dataPermission)) {
            String id = mappedStatement.getId();
            log.info("\n 数据权限过滤 method -> {}", id);
            String originSql = boundSql.getSql();
            String dataPermissionSql = dataPermissionSql(originSql, dataPermission);
            metaObject.setValue("delegate.boundSql.sql", dataPermissionSql);
            log.info("\n originSql -> {} \n dataPermissionSql: {}", originSql, dataPermissionSql);
        }
    }
    return invocation.proceed();
}
 
Example 5
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
private InvocationContext processIntercept(InvocationContext context)throws Throwable {
	MappedStatement ms = context.getMappedStatement();
	Pagination pagination = context.getPagination();
	
	
	BoundSql boundSql = ms.getBoundSql(pagination.getCriteria());
	
	// counting
	if(pagination.isNeedTotalCount()){
		Integer counting = new CountingExecutor(ms, dialect, boundSql).execute();
		pagination.setTotalCount(counting);
	}
	// paging
	String pagingSql = dialect.getPagingSQL(boundSql.getSql().trim());
	
	// cpy mappings
	List<ParameterMapping> mappings = new ArrayList<ParameterMapping>();
	if(boundSql.getParameterMappings() != null){
		List<ParameterMapping> tmpMappings = boundSql.getParameterMappings();
		for (int i = 0; i < tmpMappings.size(); i++) {
			mappings.add(tmpMappings.get(i));
		}
	}
	
	BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), pagingSql, mappings, boundSql.getParameterObject());
	cpyAndAppendParameters(ms, pagination, boundSql, newBoundSql);
	
	InvocationContext newContext = new InvocationContext();
       MappedStatement newms = cloneMappedStatement(ms, newBoundSql);
       newContext.setMappedStatement(newms);
       newContext.setPagination(pagination);
       
       return newContext;
}
 
Example 6
Source File: DataScopeInterceptor.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) realTarget(invocation.getTarget());
    MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
    MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");

    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return invocation.proceed();
    }

    BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
    String originalSql = boundSql.getSql();
    Object parameterObject = boundSql.getParameterObject();

    //查找参数中包含DataScope类型的参数
    DataScope dataScope = findDataScopeObject(parameterObject);

    if (dataScope == null) {
        return invocation.proceed();
    } else {
        String scopeName = dataScope.getScopeName();
        List<Integer> deptIds = dataScope.getDeptIds();
        String join = join(deptIds, ",");
        originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";

        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
        return invocation.proceed();
    }
}
 
Example 7
Source File: MetricInterceptor.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    BoundSql boundSql = ((StatementHandler) invocation.getTarget()).getBoundSql();

    String sql = boundSql.getSql().replaceAll("\\s*\\n\\s*", " ");
    List<Object> parameters = new ArrayList<>();
    if (configuration.isShowQueryWithParameters()) {
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        Object parameterObject = boundSql.getParameterObject();
        MetaObject metaObject = MyBatisUtils.getMetaObject(parameterObject);
        if (parameterMappings.size() == 1 && !(parameterObject instanceof Map) &&
                !metaObject.hasGetter(parameterMappings.get(0).getProperty())) {
            parameters.add(parameterObject);
        } else {
            parameterMappings.forEach(pm -> parameters.add(metaObject.getValue(pm.getProperty())));
        }
    }

    StopWatch stopWatch = StopWatch.createStarted();
    Object proceed = invocation.proceed();
    long time = stopWatch.getTime();
    if (time > configuration.getSlowQueryThresholdInMillis()) {
        if (parameters.isEmpty()) {
            logger.error(String.format("[SLOW Query took %s ms] %s", time, sql));
        } else {
            logger.error(String.format("[SLOW Query took %s ms, Parameters: %s] %s ", time, parameters, sql));
        }
        BiConsumer<String, Long> slowSqlHandler = configuration.getSlowQueryHandler();
        if (slowSqlHandler != null) {
            slowSqlHandler.accept(sql, time);
        }
    } else if (configuration.isShowQuery()) {
        if (parameters.isEmpty()) {
            logger.info(String.format("[Query took %s ms] %s", time, sql));
        } else {
            logger.info(String.format("[Query took %s ms, Parameters: %s] %s ", time, parameters, sql));
        }
    }
    return proceed;
}
 
Example 8
Source File: InsertEnhancement.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    String sqlUpperCase = sql.toUpperCase();
    if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT &&
            !sqlUpperCase.startsWith("INSERT INTO ") && sqlUpperCase.startsWith("INSERT ")) {
        Matcher matcher = PATTERN_LITERAL_COLUMNS.matcher(sql = sql.substring(7));
        if (!matcher.find()) {
            throw new IllegalStateException("Found INSERT statement but no column is specified");
        }

        String literalColumns = matcher.group();
        Class<?> entityType = MapperUtils.getEntityTypeFromMapper
                (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");
        BinaryTuple<List<String>, List<String>> propertiesAndColumns =
                SqlUtils.getPropertiesAndColumnsFromLiteralColumns(literalColumns, entityType, mapUnderscoreToCamelCase);

        List<?> entities = boundSql.getParameterObject() instanceof Map ?
                (List<?>) ((Map) boundSql.getParameterObject()).get("param1") :
                Collections.singletonList(Objects.requireNonNull(boundSql.getParameterObject(),
                        "ParameterObject mustn't be null"));
        if (entities.isEmpty()) {
            throw new IllegalArgumentException("Can't insert empty list");
        } else {
            String additionalStatement = sql.substring(literalColumns.length());
            org.apache.ibatis.session.Configuration configuration =
                    (org.apache.ibatis.session.Configuration) metaObject.getValue("delegate.configuration");
            Object parameterObject = buildParameterObject(entities);
            metaObject.setValue("delegate.boundSql.sql",
                    buildSql(entityType, propertiesAndColumns.second(), entities.size(), additionalStatement));
            metaObject.setValue("delegate.boundSql.parameterMappings",
                    MyBatisUtils.getListParameterMappings(configuration, propertiesAndColumns.first(), entities.size()));
            metaObject.setValue("delegate.boundSql.parameterObject", parameterObject);
            MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
                    .setValue("parameterObject", parameterObject);
        }
    }
}
 
Example 9
Source File: PageInterceptor.java    From Zebra with Apache License 2.0 5 votes vote down vote up
private Object queryCount(Invocation invocation, Object[] args, MappedStatement ms, BoundSql boundSql)
		throws InvocationTargetException, IllegalAccessException {
	MappedStatement countRowStatement = COUNT_MAPPED_STATS.get(ms.getId());

	if (countRowStatement == null) {
		String countSql = dialect.getCountSql(boundSql.getSql());
		BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(),
				boundSql.getParameterObject());
		MetaObject mo = (MetaObject) ReflectionUtils.getFieldValue(boundSql, "metaParameters");
		ReflectionUtils.setFieldValue(newBoundSql, "metaParameters", mo);
		Object additionalParameters = ReflectionUtils.getFieldValue(boundSql, "additionalParameters");
		ReflectionUtils.setFieldValue(newBoundSql, "additionalParameters", additionalParameters);
		List<ResultMap> resultMaps = new ArrayList<ResultMap>();
		ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), int.class,
				EMPTY_RESULTMAPPING).build();
		resultMaps.add(resultMap);
		countRowStatement = buildMappedStatement(ms, new SqlSourceWrapper(newBoundSql), ms.getId() + "_COUNT",
				resultMaps);
	}

	args[0] = countRowStatement;
	args[2] = new RowBounds();
	args[3] = null;

	try {
		DaoContextHolder.setSqlName(buildDaoName(ms.getId()) + "_COUNT");
		return invocation.proceed();
	} finally {
		DaoContextHolder.clearSqlName();
	}
}
 
Example 10
Source File: SelectOrCount.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    Class<?> entityType = MapperUtils.getEntityTypeFromMapper
            (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append(mappedStatement.getId().endsWith("count") ? "SELECT COUNT(*) FROM " : "SELECT * FROM ")
            .append(EntityUtils.getTableName(entityType, configuration.getNameAdaptor()));

    Map<?, ?> parameterMap = (Map<?, ?>) boundSql.getParameterObject();
    Object entity = parameterMap.get("param1");
    List<String> properties;
    String[] conditionalProperties = (String[]) (parameterMap.containsKey("param2") ?
            parameterMap.get("param2") : parameterMap.get("param3"));
    if (conditionalProperties.length == 0) {
        properties = EntityUtils.getProperties(entity, true);
    } else {
        properties = Arrays.asList(conditionalProperties);
    }

    if (!properties.isEmpty()) {
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");
        List<String> columns = properties.stream()
                .map(it -> SqlUtils.normalizeColumn(it, mapUnderscoreToCamelCase)).collect(Collectors.toList());
        SqlUtils.appendWhere(sqlBuilder, columns.stream());
    }

    List<ParameterMapping> parameterMappings = MyBatisUtils.getParameterMappings
            ((org.apache.ibatis.session.Configuration)
                    metaObject.getValue("delegate.configuration"), properties);
    MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
            .setValue("parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterMappings", parameterMappings);
    metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
}
 
Example 11
Source File: AutoParameterMappingPreprocessor.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    Object parameterObject = boundSql.getParameterObject();
    if (parameterMappings.isEmpty() && parameterObject instanceof Map) {
        int parameterCount = SqlUtils.countPlaceholders(boundSql.getSql());
        if (parameterCount > 0) {
            Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration");
            for (int size = ((Map<?, ?>) parameterObject).size() / 2, i = size - parameterCount + 1; i <= size; i++) {
                parameterMappings.add(new ParameterMapping.Builder
                        (configuration, "param" + i, Object.class).build());
            }
        }
    }
}
 
Example 12
Source File: PageInterceptor.java    From ssm-demo with Apache License 2.0 5 votes vote down vote up
/**
 * 拦截后要执行的方法
 */
public Object intercept(Invocation invocation) throws Throwable {
	// 对于StatementHandler其实只有两个实现类,
	// 一个是RoutingStatementHandler,
	// 另一个是抽象类BaseStatementHandler,
	// BaseStatementHandler有三个子类,分别是SimpleStatementHandler,PreparedStatementHandler和CallableStatementHandler,
	// SimpleStatementHandler是用于处理Statement的,
	// PreparedStatementHandler是处理PreparedStatement的,
	// 而CallableStatementHandler是 处理CallableStatement的。
	// Mybatis在进行Sql语句处理的时候都是建立的RoutingStatementHandler,而在RoutingStatementHandler里面拥有一个StatementHandler类型的delegate属性,
	// RoutingStatementHandler会依据Statement的不同建立对应的BaseStatementHandler,
	// 即SimpleStatementHandler、PreparedStatementHandler或CallableStatementHandler,
	// 在RoutingStatementHandler里面所有StatementHandler接口方法的实现都是调用的delegate对应的方法。
	// 我们在PageInterceptor类上已经用@Signature标记了该Interceptor只拦截StatementHandler接口的prepare方法,
	// 又因为Mybatis只有在建立RoutingStatementHandler的时候是通过Interceptor的plugin方法进行包裹的,
	// 所以我们这里拦截到的目标对象肯定是RoutingStatementHandler对象。
	RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();

	// 通过反射获取到当前RoutingStatementHandler对象的delegate属性
	StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");

	// 获取到当前StatementHandler的boundSql,这里不管是调用handler.getBoundSql()还是直接调用delegate.getBoundSql()结果是一样的,因为之前已经说过了
	// RoutingStatementHandler实现的所有StatementHandler接口方法里面都是调用的delegate对应的方法。
	BoundSql boundSql = delegate.getBoundSql();

	// 拿到当前绑定Sql的参数对象,就是我们在调用对应的Mapper映射语句时所传入的参数对象
	Object obj = boundSql.getParameterObject();

	// 这里我们简单的通过传入的是Page对象就认定它是需要进行分页操作的。
	if (obj instanceof Page<?>) {

		Page<?> page = (Page<?>) obj;

		// 通过反射获取delegate父类BaseStatementHandler的mappedStatement属性
		MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");

		// 拦截到的prepare方法参数是一个Connection对象
		Connection connection = (Connection) invocation.getArgs()[0];

		// 获取当前要执行的Sql语句,也就是我们直接在Mapper映射语句中写的Sql语句
		String sql = boundSql.getSql();

		// 给当前的page参数对象设置总记录数
		this.setTotalRecord(page, mappedStatement, connection);

		// 获取分页Sql语句
		String pageSql = this.getPageSql(page, sql);

		// 利用反射设置当前BoundSql对应的sql属性为我们建立好的分页Sql语句
		ReflectUtil.setFieldValue(boundSql, "sql", pageSql);

	}

	return invocation.proceed();
}
 
Example 13
Source File: DataScopeInterceptor.java    From pig with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    this.sqlParser(metaObject);
    // 先判断是不是SELECT操作
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return invocation.proceed();
    }

    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    String originalSql = boundSql.getSql();
    Object parameterObject = boundSql.getParameterObject();

    //查找参数中包含DataScope类型的参数
    DataScope dataScope = findDataScopeObject(parameterObject);

    if (dataScope == null) {
        return invocation.proceed();
    } else {
        String scopeName = dataScope.getScopeName();
        List<Integer> deptIds = dataScope.getDeptIds();
        if(StrUtil.isNotBlank(scopeName) && CollectionUtil.isNotEmpty(deptIds)){
            String join = CollectionUtil.join(deptIds, ",");
            originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
            metaObject.setValue("delegate.boundSql.sql", originalSql);
        }
        return invocation.proceed();
    }
}
 
Example 14
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 15
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;
}
 
Example 16
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 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: DatabaseRouteHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {

    Object[] objects = invocation.getArgs();
    MappedStatement ms = (MappedStatement) objects[0];
    Object parameterObject = objects[1];

    // TypeHandlerRegistry typeHandlerRegistry =
    // ms.getConfiguration().getTypeHandlerRegistry();

    if (ignoreMappedStatementIds.contains(ms.getId())) {
        return null;
    }
    String namespace = ms.getId().substring(0, ms.getId().lastIndexOf(SPIT_POINT));
    //策略配置忽略
    if (ignoreTablesMapperNameSpace.contains(namespace)) {
        return null;
    }

    BoundSql boundSql = ms.getBoundSql(parameterObject);

    Object parameterObject2 = boundSql.getParameterObject();
    System.out.println(parameterObject2);

    //是否需要分库
    boolean requiredShard = isRequiredShard(boundSql.getSql(), ms.getSqlCommandType(),
            namespace);

    if (requiredShard) {
        //先检查是否已经设置
        Object shardFieldValue = getShardFieldValue(ms.getId(), parameterObject);
        if (shardFieldValue == null) {
            logger.error("方法{}无法获取分库字段{}的值", ms.getId(), shardStrategy.shardEntityField());
        } else {
            int dbIndex = shardStrategy.assigned(shardFieldValue);
            //指定数据库分库序列
            DataSourceContextHolder.get().setDbIndex(dbIndex);
        }
    }
    return null;
}
 
Example 19
Source File: Update.java    From mybatis-boost with MIT License 4 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    Class<?> entityType = MapperUtils.getEntityTypeFromMapper
            (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("UPDATE ").append(EntityUtils.getTableName(entityType, configuration.getNameAdaptor()));

    boolean partial = mappedStatement.getId().contains("Partial");
    boolean selective = mappedStatement.getId().contains("Selective");

    Map<?, ?> parameterMap = (Map<?, ?>) boundSql.getParameterObject();
    Object entity = parameterMap.get("param1");
    List<String> properties;
    String[] conditionalProperties;
    if (!partial) {
        properties = EntityUtils.getProperties(entity, selective);
        conditionalProperties = (String[]) parameterMap.get("param2");
    } else {
        String[] candidateProperties = (String[]) parameterMap.get("param2");
        properties = PropertyUtils.buildPropertiesWithCandidates(candidateProperties, entity, selective);
        conditionalProperties = (String[]) parameterMap.get("param3");
    }
    if (conditionalProperties.length == 0) {
        conditionalProperties = new String[]{EntityUtils.getIdProperty(entityType)};
    }
    PropertyUtils.rebuildPropertiesWithConditions(properties, entityType, conditionalProperties);

    if (!properties.isEmpty()) {
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");
        List<String> columns = properties.stream()
                .map(it -> SqlUtils.normalizeColumn(it, mapUnderscoreToCamelCase)).collect(Collectors.toList());
        sqlBuilder.append(" SET ");
        columns.stream().limit(columns.size() - conditionalProperties.length)
                .forEach(c -> sqlBuilder.append(c).append(" = ?, "));
        sqlBuilder.setLength(sqlBuilder.length() - 2);
        SqlUtils.appendWhere(sqlBuilder, columns.stream().skip(columns.size() - conditionalProperties.length));
    }

    List<ParameterMapping> parameterMappings = MyBatisUtils.getParameterMappings
            ((org.apache.ibatis.session.Configuration)
                    metaObject.getValue("delegate.configuration"), properties);
    MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
            .setValue("parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterMappings", parameterMappings);
    metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
}
 
Example 20
Source File: PageStatementInterceptor.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler handler = (StatementHandler) invocation.getTarget();

    // 获取MappedStatement,Configuration对象
    MetaObject metaObject =
            MetaObject.forObject(handler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    String statement = mappedStatement.getId();
    if (!isPageSql(statement,metaObject.getValue("boundSql.parameterObject"))) {
        return invocation.proceed();
    }

    Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration");
    Executor executor = (Executor) metaObject.getValue("delegate.executor");

    // 获取分页参数
    BoundSql boundSql = handler.getBoundSql();
    QPageQuery pageQuery = (QPageQuery) boundSql.getParameterObject();
    String countStatement = buildCountStatement(statement);
    List<Integer> counts = executor.query(configuration.
            getMappedStatement(countStatement), pageQuery, RowBounds.DEFAULT, null);

    int count = 0;
    if (counts != null && !counts.isEmpty()) {
        count = counts.get(0) == null ? 0 : counts.get(0);
    }

    if (pageQuery.getPagination() == null) {
        pageQuery.setPagination(new Pagination());
    }
    pageQuery.getPagination().setTotalRecord(count);

    String sql = boundSql.getSql();
    if (logger.isDebugEnabled()) {
        logger.debug("raw SQL : " + sql);
    }

    if (sql == null || sql.isEmpty() || sql.contains(" limit ")) {
        return invocation.proceed();
    }

    String originalSql = (String) metaObject.getValue("delegate.boundSql.sql");
    metaObject.setValue("delegate.boundSql.sql",
            getLimitString(originalSql, pageQuery.getPagination().getStart(),
                    pageQuery.getPagination().getSize()));
    metaObject.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
    metaObject.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);

    if (logger.isDebugEnabled()) {
        logger.debug("pagination SQL : " + sql);
    }
    return invocation.proceed();
}