Java Code Examples for org.apache.ibatis.plugin.Invocation#getArgs()

The following examples show how to use org.apache.ibatis.plugin.Invocation#getArgs() . 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 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: SsensitiveOperProtectHandler.java    From oneplatform 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(ExceptionCode.OPTER_NOT_ALLOW.code, "当前已开启敏感操作保护");
	}
	return null;
}
 
Example 10
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 11
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 12
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();
}
 
Example 13
Source File: CacheHandler.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {

	Object[] args = invocation.getArgs();
	MappedStatement mt = (MappedStatement)args[0]; 

	concurrentLockKey.remove();
	
	boolean getLock = false;
	String cacheKey = null;
	if(mt.getSqlCommandType().equals(SqlCommandType.SELECT)){	
		//事务方法内部的查询不走缓存
		if(MybatisRuntimeContext.isTransactionalOn()){
			if(logger.isDebugEnabled())logger.debug(">>auto_cache_process  isTransactionalOn SKIP -> mapperId:{}",mt.getId());
			return null;
		}
		//按主键查询
		QueryMethodCache cacheInfo = getQueryMethodCache(mt.getId());
		if(cacheInfo == null)return null;
		//
		if(skipCache(cacheInfo)){
			if(logger.isDebugEnabled())logger.debug(">>auto_cache_process cache_mark_expired SKIP -> userId:{}, mapperId:{}",MybatisRuntimeContext.getCurrentUserId(),mt.getId());
			return null;
		}
		cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]);
		//并发控制防止缓存穿透
		if(!cacheInfo.concurrency){
			concurrentLockKey.set("concurrent:" + cacheKey);
			getLock = getCacheProvider().setnx(concurrentLockKey.get(), "1", 30);
			if(!getLock){
				if(logger.isDebugEnabled())logger.debug(">>auto_cache_process not_getConcurrentLock BLOCK -> mapperId:{}",mt.getId());
				return BLOCK_ON_CONCURRENT_LOCK_RETURN;
			}
			if(logger.isDebugEnabled())logger.debug(">>auto_cache_process getConcurrentLock CONTINUE -> mapperId:{}",mt.getId());
		}
		
		Object cacheObject = null;
		boolean nullPlaceholder = false;
		//
		if(!cacheInfo.isSecondQueryById()){
			//从缓存读取
			cacheObject = getCacheProvider().get(cacheKey);
			nullPlaceholder = nullValueCache && NULL_PLACEHOLDER.equals(cacheObject);
			if(StringUtils.isNotBlank(cacheInfo.refKey) && (nullPlaceholder || cacheObject == null)){
				cacheObject = getCacheProvider().get(cacheInfo.refKey);
				nullPlaceholder = nullValueCache && NULL_PLACEHOLDER.equals(cacheObject);
			}
			if(nullPlaceholder){
				logger.debug(">>auto_cache_process method[{}] find NULL_PLACEHOLDER result from cacheKey:{}",mt.getId(),cacheKey);
			}else if(cacheObject != null){
				logger.debug(">>auto_cache_process method[{}] find result from cacheKey:{}",mt.getId(),cacheKey);
			}
		}else{
			//新根据缓存KEY找到与按ID缓存的KEY
			String refCacheKey = nullValueCache ? getCacheProvider().get(cacheKey) : getCacheProvider().getStr(cacheKey);
			if(refCacheKey != null){
				if(nullPlaceholder = (nullValueCache && NULL_PLACEHOLDER.equals(refCacheKey))){
					cacheObject = NULL_PLACEHOLDER;
				}else{						
					cacheObject = getCacheProvider().get(refCacheKey);
					if(cacheObject != null && logger.isDebugEnabled())logger.debug(">>auto_cache_process method[{}] find result from cacheKey:{} ,ref by:{}",mt.getId(),refCacheKey,cacheKey);
				}
			}
		}
		
		if(nullPlaceholder){
			cacheObject = new ArrayList<>(0);
		}else if(cacheObject != null && !(cacheObject instanceof Collection)){						
			cacheObject = Arrays.asList(cacheObject);
		}
		
		return cacheObject;
	} else{
		tryRemarkCleanRalationCache(mt);
	}
	
	return null;

}
 
Example 14
Source File: CatMybatisPlugin.java    From radar with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	String jdbcUrl = "Notsupported Url";
	String method = "Notsupported Method";
	String sql = "Notsupported SQL";
	String classMethod = "Notsupported Class Method";

	try {
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];

		DataSource ds = mappedStatement.getConfiguration().getEnvironment().getDataSource();

		if (ds instanceof com.mchange.v2.c3p0.ComboPooledDataSource) {
			com.mchange.v2.c3p0.ComboPooledDataSource c3p0Ds = (com.mchange.v2.c3p0.ComboPooledDataSource) ds;
			jdbcUrl = c3p0Ds.getJdbcUrl();
		} else if (ds instanceof org.apache.tomcat.jdbc.pool.DataSource) {
			org.apache.tomcat.jdbc.pool.DataSource tDs = (org.apache.tomcat.jdbc.pool.DataSource) ds;
			jdbcUrl = tDs.getUrl();
		} else if (ds instanceof com.alibaba.druid.pool.DruidDataSource) {
			com.alibaba.druid.pool.DruidDataSource dDs = (com.alibaba.druid.pool.DruidDataSource) ds;
			jdbcUrl = dDs.getUrl();
		} else {
			jdbcUrl = dbUrl;
		}

		// 得到 类名-方法
		String[] strArr = mappedStatement.getId().split("\\.");
		classMethod = strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];
		// 得到sql语句
		Object parameter = null;
		if (invocation.getArgs().length > 1) {
			parameter = invocation.getArgs()[1];
		}

		BoundSql boundSql = mappedStatement.getBoundSql(parameter);
		Configuration configuration = mappedStatement.getConfiguration();
		sql = showSql(configuration, boundSql);

	} catch (Exception ex) {

	}

	if (isFullLog() && sql.toLowerCase().indexOf("select") == -1 && sql.toLowerCase().indexOf("instance") != -1
			&& sql.toLowerCase().indexOf("update instance set heart_time=now()") == -1) {
		log.info("sql5_is_{}", sql);
	}
	Transaction t = Tracer.newTransaction("SQL", classMethod);
	method = sql.substring(0, sql.indexOf(" "));

	Tracer.logEvent("SQL.Method", method);
	Tracer.logEvent("SQL.Database", jdbcUrl);
	Tracer.logEvent("SQL.Statement", method, Transaction.SUCCESS,
			sql.length() > 1000 ? sql.substring(0, 1000) : sql);

	Object returnObj = null;
	try {
		returnObj = invocation.proceed();
		t.setStatus(Transaction.SUCCESS);
	} catch (Exception e) {
		if (sql.indexOf("soa_lock") != -1 && sql.indexOf("insert") != -1) {
			t.setStatus(Transaction.SUCCESS);
		} else {
			t.setStatus(e);
			Tracer.logError(e);
			throw e;
		}			
	} finally {
		t.complete();
	}
	return returnObj;
}
 
Example 15
Source File: CatMybatisPlugin.java    From pmq with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	String sql = "";
	String classMethod = "Notsupported Class Method";
	if (soaConfig.getCatSql() == 1) {
		try {
			//String jdbcUrl = "Notsupported Url";
			//String method = "Notsupported Method";

			// DataSource ds = null;
			MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
			// ds =
			// mappedStatement.getConfiguration().getEnvironment().getDataSource();
			// if (ds instanceof com.mchange.v2.c3p0.ComboPooledDataSource)
			// {
			// com.mchange.v2.c3p0.ComboPooledDataSource c3p0Ds =
			// (com.mchange.v2.c3p0.ComboPooledDataSource) ds;
			// jdbcUrl = c3p0Ds.getJdbcUrl();
			// } else if (ds instanceof
			// org.apache.tomcat.jdbc.pool.DataSource)
			// {
			// org.apache.tomcat.jdbc.pool.DataSource tDs =
			// (org.apache.tomcat.jdbc.pool.DataSource) ds;
			// jdbcUrl = tDs.getUrl();
			// } else if (ds instanceof
			// com.alibaba.druid.pool.DruidDataSource)
			// {
			// @SuppressWarnings("resource")
			// com.alibaba.druid.pool.DruidDataSource dDs =
			// (com.alibaba.druid.pool.DruidDataSource) ds;
			// jdbcUrl = dDs.getUrl();
			// } else if (ds instanceof DynamicDataSource) {
			// com.alibaba.druid.pool.DruidDataSource dDs =
			// (com.alibaba.druid.pool.DruidDataSource) ((DynamicDataSource)
			// ds)
			// .getDataSource();
			// jdbcUrl = dDs.getUrl();
			// } else {
			// jdbcUrl = dbUrl;
			// }

			// 得到 类名-方法
			String[] strArr = mappedStatement.getId().split("\\.");
			classMethod = strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];
			// 得到sql语句
			Object parameter = null;
			if (invocation.getArgs().length > 1) {
				parameter = invocation.getArgs()[1];
			}

			BoundSql boundSql = mappedStatement.getBoundSql(parameter);
			Configuration configuration = mappedStatement.getConfiguration();
			sql = showSql(configuration, boundSql);
			if(classMethod.equals(soaConfig.getCatSqlKey())){
				log.info("the sql is:"+sql);
			}
			

		} catch (Exception ex) {

		}
	}
	Transaction t = null;
	if (soaConfig.getCatSql() == 1) {
		t = Tracer.newTransaction("SQL", classMethod);
	}
	// method = sql.substring(0, sql.indexOf(" "));
	// Tracer.logEvent("SQL.Method", method);
	// Tracer.logEvent("SQL.Database", jdbcUrl);
	// Tracer.logEvent("SQL.Statement", method, Transaction.SUCCESS,
	// sql.length() > 1000 ? sql.substring(0, 1000) : sql);

	Object returnObj = null;
	try {
		returnObj = invocation.proceed();
		if (t != null) {
			t.setStatus(Transaction.SUCCESS);
		}
	} catch (Exception e) {
		if (t != null) {
			t.addData("sql", sql);
			t.setStatus(e);
		}
		throw e;
	} finally {
		if (t != null) {
			t.complete();
		}
	}
	return returnObj;
}
 
Example 16
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 17
Source File: CacheHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {

    Object[] args = invocation.getArgs();
    MappedStatement mt = (MappedStatement) args[0];

    if (mt.getSqlCommandType().equals(SqlCommandType.SELECT)) {
        //按主键查询
        QueryMethodCache cacheInfo = getQueryMethodCache(mt.getId());
        if (cacheInfo == null) { return null; }
        final String cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]);

        Object cacheObject = null;
        boolean nullPlaceholder = false;
        //按主键查询以及标记非引用关系的缓存直接读取缓存
        if (cacheInfo.isSecondQueryById() == false) {
            //从缓存读取
            cacheObject = getCacheProvider().get(cacheKey);
            nullPlaceholder = nullValueCache && NULL_PLACEHOLDER.equals(cacheObject);
            if (nullPlaceholder) {
                logger.debug(
                        "_autocache_ method[{}] find NULL_PLACEHOLDER result from cacheKey:{}",
                        mt.getId(), cacheKey);
            } else if (cacheObject != null) {
                logger.debug("_autocache_ method[{}] find result from cacheKey:{}", mt.getId(),
                        cacheKey);
            }
        } else {
            //新根据缓存KEY找到与按ID缓存的KEY
            String refCacheKey = nullValueCache ? getCacheProvider().get(cacheKey)
                    : getCacheProvider().getStr(cacheKey);
            if (refCacheKey != null) {
                if (nullPlaceholder = (nullValueCache
                        && NULL_PLACEHOLDER.equals(refCacheKey))) {
                    cacheObject = NULL_PLACEHOLDER;
                } else {
                    cacheObject = getCacheProvider().get(refCacheKey);
                    if (cacheObject != null && logger.isDebugEnabled()) {
                        logger.debug(
                                "_autocache_ method[{}] find result from cacheKey:{} ,ref by:{}",
                                mt.getId(), refCacheKey, cacheKey);
                    }
                }
            }
        }

        if (nullPlaceholder) {
            cacheObject = new ArrayList<>();
        } else if (cacheObject != null && !(cacheObject instanceof Collection)) {
            cacheObject = new ArrayList<>(Arrays.asList(cacheObject));
        }

        return cacheObject;
        //非按主键删除的方法需求先行查询出来并删除主键缓存
    } else if (mt.getSqlCommandType().equals(SqlCommandType.DELETE)
            && !updateCacheMethods.containsKey(mt.getId())) {
        String mapperNameSpace = mt.getId().substring(0, mt.getId().lastIndexOf(SPLIT_PONIT));
        Executor executor = (Executor) invocation.getTarget();
        removeCacheByUpdateConditon(executor, mt, mapperNameSpace, args);
    }

    return null;

}
 
Example 18
Source File: OffsetLimitInterceptor.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
public Object intercept(final Invocation invocation) throws Throwable {
       final Executor executor = (Executor) invocation.getTarget();
       final Object[] queryArgs = invocation.getArgs();
       final MappedStatement ms = (MappedStatement)queryArgs[MAPPED_STATEMENT_INDEX];
       final Object parameter = queryArgs[PARAMETER_INDEX];
       final RowBounds rowBounds = (RowBounds)queryArgs[ROWBOUNDS_INDEX];
       final PageBounds pageBounds = new PageBounds(rowBounds);

       if(pageBounds.getOffset() == RowBounds.NO_ROW_OFFSET
               && pageBounds.getLimit() == RowBounds.NO_ROW_LIMIT
               && pageBounds.getOrders().isEmpty()){
           return invocation.proceed();
       }

       final Dialect dialect;
       try {
           Class clazz = Class.forName(dialectClass);
           Constructor constructor = clazz.getConstructor(MappedStatement.class, Object.class, PageBounds.class);
           dialect = (Dialect)constructor.newInstance(new Object[]{ms, parameter, pageBounds});
       } catch (Exception e) {
           throw new ClassNotFoundException("Cannot create dialect instance: "+dialectClass,e);
       }

       final BoundSql boundSql = ms.getBoundSql(parameter);

       queryArgs[MAPPED_STATEMENT_INDEX] = copyFromNewSql(ms,boundSql,dialect.getPageSQL(), dialect.getParameterMappings(), dialect.getParameterObject());
       queryArgs[PARAMETER_INDEX] = dialect.getParameterObject();
       queryArgs[ROWBOUNDS_INDEX] = new RowBounds(RowBounds.NO_ROW_OFFSET,RowBounds.NO_ROW_LIMIT);

       Boolean async = pageBounds.getAsyncTotalCount() == null ? asyncTotalCount : pageBounds.getAsyncTotalCount();
       Future<List> listFuture = call(new Callable<List>() {
           public List call() throws Exception {
               return (List)invocation.proceed();
           }
       }, async);


       if(pageBounds.isContainsTotalCount()){
           Callable<Paginator> countTask = new Callable() {
               public Object call() throws Exception {
                   Integer count;
                   Cache cache = ms.getCache();
                   if(cache != null && ms.isUseCache() && ms.getConfiguration().isCacheEnabled()){
                       CacheKey cacheKey = executor.createCacheKey(ms,parameter,new PageBounds(),copyFromBoundSql(ms,boundSql,dialect.getCountSQL(), boundSql.getParameterMappings(), boundSql.getParameterObject()));
                       count = (Integer)cache.getObject(cacheKey);
                       if(count == null){
                           count = SQLHelp.getCount(ms,executor.getTransaction(),parameter,boundSql,dialect);
                           cache.putObject(cacheKey, count);
                       }
                   }else{
                       count = SQLHelp.getCount(ms,executor.getTransaction(),parameter,boundSql,dialect);
                   }
                   return new Paginator(pageBounds.getPage(), pageBounds.getLimit(), count);
               }
           };
           Future<Paginator> countFutrue = call(countTask, async);
           return new PageList(listFuture.get(),countFutrue.get());
       }

       return listFuture.get();
}
 
Example 19
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 20
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();
    }