org.apache.ibatis.plugin.Invocation Java Examples

The following examples show how to use org.apache.ibatis.plugin.Invocation. 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: RwRouteHandler.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	//已指定强制使用
	if(MybatisRuntimeContext.isForceUseMaster()){
		logger.debug("Method[{}] force use Master..",ms.getId());
		return null;
	}
	
	//读方法
	if(ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
		//!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
		if(!ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)){				
			MybatisRuntimeContext.useSlave(true);
			logger.debug("Method[{} use Slave Strategy..",ms.getId());
		}
	}else{
		logger.debug("Method[{}] use Master Strategy..",ms.getId());
		MybatisRuntimeContext.useSlave(false);
	}
	
	return null;
}
 
Example #2
Source File: PageInterceptor.java    From dubbo-mock with Apache License 2.0 6 votes vote down vote up
/**
 * 拦截后要执行的方法
 */
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Page<?> page = PageThreadLocal.getThreadLocalPage();
    if (page == null) {
        return invocation.proceed();
    }
    PageThreadLocal.removeThreadLocalPage();
    RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();
    // 通过反射获取到当前RoutingStatementHandler对象的delegate属性
    StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");
    BoundSql boundSql = delegate.getBoundSql();
    MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");
    // 获取当前要执行的Sql语句,也就是我们直接在Mapper映射语句中写的Sql语句
    String sql = boundSql.getSql();
    // 是否查询总页数和总数据 默认为TRUE
    if (page.getTotalFlag()) {
        // 给当前的page参数对象设置总记录数
        this.setTotalRecord(page, mappedStatement, boundSql, sql);
    }

    String pageSql = this.getPageSql(sql, page);
    // 利用反射设置当前BoundSql对应的sql属性为我们建立好的分页Sql语句
    ReflectUtil.setFieldValue(boundSql, "sql", pageSql);
    return invocation.proceed();
}
 
Example #3
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object[] args = invocation.getArgs();
	
	// no paging
	if(!isPaging(args)){
		return invocation.proceed();
	}

	// process for paging
	InvocationContext context = getInvocationContext(invocation);
	InvocationContext newContext = processIntercept(context);

	swapParameter(newContext, args);
	Object result = invocation.proceed();
	
	if(result != null && result instanceof List){
		newContext.getPagination().setRecords((List<?>)result);
	}
	
	return result;
}
 
Example #4
Source File: CustomPageInterceptor.java    From spring-boot-starter-dao with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object object=invocation.getArgs()[0];
	if(object instanceof MappedStatement){
		MappedStatement  statement=(MappedStatement) object;
		Configuration config = statement.getConfiguration();
		DataSource dataSource= config.getEnvironment().getDataSource();
		if(dataSource instanceof DynamicDataSource){
			DynamicDataSource dynamicDataSource=((DynamicDataSource)dataSource); 
			Dialect dialect= dynamicDataSource.getDialect();
			if(pageHelpers.containsKey(dialect)){
				log.debug("将使用{}的PageHelper....",dialect);
				return pageHelpers.get(dialect).intercept(invocation);
			}else{
				log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
			}
		}else{
			log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
		}
	}else{
		log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
	}
	return pageHelper.intercept(invocation);
}
 
Example #5
Source File: RwRouteHandler.java    From azeroth with Apache License 2.0 6 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {

    Object[] objects = invocation.getArgs();
    MappedStatement ms = (MappedStatement) objects[0];
    //已指定强制使用
    if (DataSourceContextHolder.get().isForceUseMaster()) {
        logger.debug("Method[{}] force use Master..", ms.getId());
        return null;
    }

    //读方法
    if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
        //!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
        if (!ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
            DataSourceContextHolder.get().useSlave(true);
            logger.debug("Method[{} use Slave Strategy..", ms.getId());
        }
    } else {
        logger.debug("Method[{}] use Master Strategy..", ms.getId());
        DataSourceContextHolder.get().useSlave(false);
    }

    return null;
}
 
Example #6
Source File: SqlUtil.java    From genericdao with Artistic License 2.0 6 votes vote down vote up
/**
     * Mybatis拦截器方法
     *
     * @param invocation 拦截器入参
     * @return 返回执行结果
     * @throws Throwable 抛出异常
     */
    public Object processPage(Invocation invocation) throws Throwable {
        try{
            Object result = _processPage(invocation);
            clearLocalPage();
            //扩展当前分页对象,使用spring的分页对象
            if(result instanceof PageHelper){
//            	MybatisPage page = (MybatisPage) result ;
//            	Page resultPage = new PageImpl(page , new PageRequest(page.getPageNum(), page.getPageSize()), page.getTotal()) ;
//            	return resultPage ;
            	return new MybatisPageImpl((PageHelper) result) ;
            }
            return result;
        } finally {
            clearLocalPage();
        }
    }
 
Example #7
Source File: CustomHandlerInterceptor.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object[] args = invocation.getArgs();
	MappedStatement ms = (MappedStatement) args[0];
	Object parameter = args[1];
	if (args[3] != null) {
		return invocation.proceed();
	}
	//用自定义handler
	CustomHandler handler = HandlerResolver.resolve(ms, parameter);
	if (handler == null) {
		return invocation.proceed();
	}
	args[3] = handler;
	invocation.proceed();
	return handler.getResult();
}
 
Example #8
Source File: MySqlPagingPlugin.java    From mybatis-test with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    RowBounds rb = (RowBounds) args[ROW_BOUNDS_INDEX];
    if (rb == RowBounds.DEFAULT) {
        return invocation.proceed();
    }
    args[ROW_BOUNDS_INDEX] = RowBounds.DEFAULT;

    MappedStatement ms = (MappedStatement) args[MAPPED_STATEMENT_INDEX];
    BoundSql boundSql = ms.getBoundSql(args[PARAMETER_INDEX]);

    System.out.println();
    String sql = boundSql.getSql();
    String limit = String.format("LIMIT %d,%d", rb.getOffset(), rb.getLimit());
    sql = sql + " " + limit;

    SqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), sql, boundSql.getParameterMappings());

    Field field = MappedStatement.class.getDeclaredField("sqlSource");
    field.setAccessible(true);
    field.set(ms, sqlSource);

    return invocation.proceed();
}
 
Example #9
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 #10
Source File: PageResultInterceptor.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    // 目标对象转换
    ResultSetHandler resultSetHandler = (ResultSetHandler) invocation.getTarget();

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

    // 获取分页参数
    QPageQuery pageQuery = (QPageQuery) metaObject.getValue("boundSql.parameterObject");

    List<PageResult> result = new ArrayList<PageResult>(1);
    PageResult page = new PageResult();
    page.setPagination(pageQuery.getPagination());
    page.setResult((List) invocation.proceed());
    result.add(page);

    return result;
}
 
Example #11
Source File: PaginationInterceptor.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
    BoundSql boundSql = statementHandler.getBoundSql();
    if (log.isDebugEnabled()) {
        log.debug("raw SQL : " + boundSql.getSql());
    }
    if (boundSql.getSql() == null || boundSql.getSql().isEmpty() || boundSql.getSql().contains(" limit ")) {
        return invocation.proceed();
    }
    MetaObject metaStatementHandler = null;
    RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
    if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
        return invocation.proceed();
    }
    String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql");
    metaStatementHandler.setValue("delegate.boundSql.sql",
            getLimitString(originalSql, rowBounds.getOffset(), rowBounds.getLimit()));
    metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
    metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
    if (log.isDebugEnabled()) {
        log.debug("pagination SQL : " + boundSql.getSql());
    }
    return invocation.proceed();
}
 
Example #12
Source File: BindingLogPlugin32.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private void bindingLog(Invocation invocation) throws SQLException {

        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        StatementType statementType = ms.getStatementType();
        if (StatementType.PREPARED == statementType || StatementType.CALLABLE == statementType) {
            Log statementLog = ms.getStatementLog();
            if (isDebugEnable(statementLog)) {
                BoundSql boundSql = ms.getBoundSql(parameterObject);

                String sql = boundSql.getSql();
                List<String> parameterList = getParameters(ms, parameterObject, boundSql);
                debug(statementLog, "==> BindingLog: " + bindLogFormatter.format(sql, parameterList));
            }
        }
    }
 
Example #13
Source File: QueryLoggingInterceptor.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * {@code StatementHandler}へのクエリ実行要求をインターセプトし、 SQLのロギング機構を起動します。
 * </p>
 */
@Override
public Object intercept(Invocation invocation) throws Throwable {
    QueryInformation queryInformation = new QueryInformation((StatementHandler)invocation.getTarget());
    Object result;
    queryLogger.log(queryInformation);
    result = invocation.proceed();
    return result;
}
 
Example #14
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 #15
Source File: MybatisInterceptor.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
    Object returnValue;
    if (showDetailSql || showCostTime) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();

        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        long end = System.currentTimeMillis();
        long time = (end - start);

        String sql = getSql(configuration, boundSql, sqlId, time);
        if (slowSqlMs != 0 && time > slowSqlMs) {
            log.warn(sql);
        } else {
            log.info(sql);
        }
    } else {
        returnValue = invocation.proceed();
    }
    return returnValue;
}
 
Example #16
Source File: MybatisInterceptor.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
    Object returnValue;
    if (showDetailSql || showCostTime) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();

        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        long end = System.currentTimeMillis();
        long time = (end - start);

        String sql = getSql(configuration, boundSql, sqlId, time);
        if (slowSqlMs != 0 && time > slowSqlMs) {
            log.warn(sql);
        } else {
            log.info(sql);
        }
    } else {
        returnValue = invocation.proceed();
    }
    return returnValue;
}
 
Example #17
Source File: BindingLogPlugin32.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    if (internalLogger.isTraceEnabled()) {
        internalLogger.trace("target:" + invocation.getTarget()
                + " method:" + invocation.getMethod() + " args:" + Arrays.toString(invocation.getArgs()));
    }
    try {
        return invocation.proceed();
    } finally {
        bindingLog(invocation);
    }
}
 
Example #18
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 封装代理上下文参数
 * @param invocation
 * @return
 */
private InvocationContext getInvocationContext(Invocation invocation){
	Object[] args = invocation.getArgs();
	MappedStatement ms = (MappedStatement)args[MAPPED_STATEMENT_INDEX];
	Pagination ps = (Pagination)args[PARAMETER_INDEX];
	
	return new InvocationContext(ms, ps);
}
 
Example #19
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 #20
Source File: CustomHandlerInterceptor.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
	//只拦截Executor对象,减少目标被代理的次数
	if (target instanceof Executor) {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), interfaces, (InvocationHandler) (proxy, method, args) -> {
			if (method.getName().equals("query")) {
				return interceptor.intercept(new Invocation(target, method, args));
			}
			return method.invoke(target, args);
		});
	} else {
		return target;
	}
}
 
Example #21
Source File: ExamplePlugin.java    From mybatis-test with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    Object[] args = invocation.getArgs();
    System.out.println(method + " - " + args);
    return invocation.proceed();
}
 
Example #22
Source File: ReadOnlyForTestProtectHandler.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	if(!ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
		if(SecurityUtil.getLoginUserInfo().getName().startsWith("test")){
			throw new JeesuiteBaseException(4003, "测试账号已开启敏感操作保护");
		}
	}
	return null;
}
 
Example #23
Source File: PaginationInterceptor.java    From Mario with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

    StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
    BoundSql boundSql = statementHandler.getBoundSql();

    String sql = boundSql.getSql();
    if (StringUtils.isBlank(sql)) {
        return invocation.proceed();
    }

    //select sql do 
    if (sql.matches(SQL_SELECT_REGEX) && !Pattern.matches(SQL_COUNT_REGEX, sql)) {
        Object obj = FieldUtils.readField(statementHandler, "delegate", true);
        // 反射获取 RowBounds 对象。
        RowBounds rowBounds = (RowBounds) FieldUtils.readField(obj, "rowBounds", true);

        // 分页参数存在且不为默认值时进行分页SQL构造
        if (rowBounds != null && rowBounds != RowBounds.DEFAULT) {
            FieldUtils.writeField(boundSql, "sql", newSql(sql, rowBounds), true);

            // 一定要还原否则将无法得到下一组数据(第一次的数据被缓存了)
            FieldUtils.writeField(rowBounds, "offset", RowBounds.NO_ROW_OFFSET, true);
            FieldUtils.writeField(rowBounds, "limit", RowBounds.NO_ROW_LIMIT, true);
        }
    }

    return invocation.proceed();
}
 
Example #24
Source File: SensitiveOperProtectHandler.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	if(ms.getSqlCommandType().equals(SqlCommandType.DELETE)){
		throw new JeesuiteBaseException(4003, "当前已开启敏感操作保护");
	}
	return null;
}
 
Example #25
Source File: PreparePaginationInterceptor.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
@Override
    public Object intercept(Invocation ivk) throws Throwable {
        if (ivk.getTarget().getClass().isAssignableFrom(RoutingStatementHandler.class)) {
            final RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();
            final BaseStatementHandler delegate = (BaseStatementHandler) Reflections.getFieldValue(statementHandler, DELEGATE);
            final MappedStatement mappedStatement = (MappedStatement) Reflections.getFieldValue(delegate, MAPPED_STATEMENT);

//            //拦截需要分页的SQL
////            if (mappedStatement.getId().matches(_SQL_PATTERN)) { 
//            if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) {
                BoundSql boundSql = delegate.getBoundSql();
                //分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
                Object parameterObject = boundSql.getParameterObject();
                if (parameterObject == null) {
                    log.error("参数未实例化");
                    throw new NullPointerException("parameterObject尚未实例化!");
                } else {
                    final Connection connection = (Connection) ivk.getArgs()[0];
                    final String sql = boundSql.getSql();
                    //记录统计
                    final int count = SQLHelper.getCount(sql, connection, mappedStatement, parameterObject, boundSql, log);
                    Page<Object> page = null;
                    page = convertParameter(parameterObject, page);
                    page.setCount(count);
                    String pagingSql = SQLHelper.generatePageSql(sql, page, DIALECT);
                    if (log.isDebugEnabled()) {
                        log.debug("PAGE SQL:" + pagingSql);
                    }
                    //将分页sql语句反射回BoundSql.
                    Reflections.setFieldValue(boundSql, "sql", pagingSql);
                }
                
                if (boundSql.getSql() == null || "".equals(boundSql.getSql())){
                    return null;
                }
                
            }
//        }
        return ivk.proceed();
    }
 
Example #26
Source File: DataSessionRuleTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object intercept(final Invocation invocation) throws Throwable {
  if (failNextCommit) {
    // close connection without telling MyBatis - proceeding commit will then fail
    ((Executor) invocation.getTarget()).getTransaction().getConnection().close();
    failNextCommit = false;
  }
  return invocation.proceed();
}
 
Example #27
Source File: PageInterceptor.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object[] args = invocation.getArgs();
	Object rowBound = args[2];

	MappedStatement ms = (MappedStatement) args[0];
	if (rowBound != null) {
		RowBounds rb = (RowBounds) rowBound;

		// without pagination
		if (rb.getOffset() == RowBounds.NO_ROW_OFFSET && rb.getLimit() == RowBounds.NO_ROW_LIMIT) {
			return invocation.proceed();
		} else {
			BoundSql boundSql = ms.getBoundSql(args[1]);

			if (rowBound instanceof PageModel) {
				// physical pagination with PageModel
				PageModel pageModel = (PageModel) rowBound;
				Object count = queryCount(invocation, args, ms, boundSql);
				Object records = queryLimit(invocation, args, ms, boundSql, pageModel);

				pageModel.setRecordCount((Integer) ((List<?>) count).get(0));
				pageModel.setRecords((List<?>) records);

				return null;
			} else {
				// physical pagination with RowBounds
				return queryLimit(invocation, args, ms, boundSql, rb);
			}
		}
	} else {
		// without pagination
		return invocation.proceed();
	}
}
 
Example #28
Source File: MybatisInterceptor.java    From cicada with MIT License 5 votes vote down vote up
public Object intercept(final Invocation invocation) throws Throwable {
  final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
  Object returnValue = null;
  final long start = System.currentTimeMillis();
  returnValue = invocation.proceed();
  final long end = System.currentTimeMillis();

  final String sqlId = mappedStatement.getId();
  final int lastIndex = sqlId.lastIndexOf('.');
  final String className = sqlId.substring(0, lastIndex);
  final String methodName = sqlId.substring(lastIndex + 1);
  Tracer.getInstance().addBinaryAnnotation(className, methodName, (int) (end - start));

  return returnValue;
}
 
Example #29
Source File: LogSqlExecutionTimePlugin.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object retVal = invocation.proceed();
    long endTime = System.currentTimeMillis();
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    LOGGER.debug("SQL Statement {} took {}ms", mappedStatement.getId(), endTime-startTime);
    return retVal;
}
 
Example #30
Source File: AuditingInterceptor.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

	MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
	SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
	Object target = invocation.getArgs()[1];
	if (INSERT == sqlCommandType) {
		listener.touchForCreate(target);
	}
	else if (UPDATE == sqlCommandType) {
		listener.touchForUpdate(target);
	}
	return invocation.proceed();
}