Java Code Examples for org.apache.ibatis.executor.statement.StatementHandler

The following examples show how to use org.apache.ibatis.executor.statement.StatementHandler. These examples are extracted from open source projects. 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 Project: FEBS-Cloud   Source File: DataPermissionInterceptor.java    License: 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 2
Source Project: joyqueue   Source File: PaginationInterceptor.java    License: 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 3
Source Project: Aooms   Source File: RecordInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
    //StatementHandler statementHandler = (StatementHandler)realTarget(invocation.getTarget());
    //MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    //Object parameterObject = metaObject.getValue("delegate.boundSql.parameterObject");
    //MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

    StatementHandler target = MetaObjectAssistant.getTarget(invocation, StatementHandler.class);
    MetaObject metaObject = MetaObjectAssistant.getMetaObject(target);
    Object parameterObject = MetaObjectAssistant.getParameterObject(metaObject);
    if(parameterObject == null) return invocation.proceed();

    // parameterObject is not a vo , skip RecordInterceptor
    if(parameterObject.getClass() != Record.class){
        return invocation.proceed();
    }

    // vo oper process
    IRecordOper recordOper = recordOperRouting.route(metaObject);
    recordOper.process();

    Object value = invocation.proceed();
    return value;
}
 
Example 4
Source Project: dubbo-mock   Source File: PageInterceptor.java    License: 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 5
Source Project: mybaties   Source File: ReuseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
  Statement stmt;
  //得到绑定的SQL语句
  BoundSql boundSql = handler.getBoundSql();
  String sql = boundSql.getSql();
  //如果缓存中已经有了,直接得到Statement
  if (hasStatementFor(sql)) {
    stmt = getStatement(sql);
  } else {
    //如果缓存没有找到,则和SimpleExecutor处理完全一样,然后加入缓存
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection);
    putStatement(sql, stmt);
  }
  handler.parameterize(stmt);
  return stmt;
}
 
Example 6
Source Project: mybaties   Source File: BatchExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  final Configuration configuration = ms.getConfiguration();
  final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  final BoundSql boundSql = handler.getBoundSql();
  final String sql = boundSql.getSql();
  final Statement stmt;
  if (sql.equals(currentSql) && ms.equals(currentStatement)) {
    int last = statementList.size() - 1;
    stmt = statementList.get(last);
    BatchResult batchResult = batchResultList.get(last);
    batchResult.addParameterObject(parameterObject);
  } else {
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    currentSql = sql;
    currentStatement = ms;
    statementList.add(stmt);
    batchResultList.add(new BatchResult(ms, sql, parameterObject));
  }
  handler.parameterize(stmt);
  handler.batch(stmt);
  return BATCH_UPDATE_RETURN_VALUE;
}
 
Example 7
Source Project: mybaties   Source File: BatchExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
    throws SQLException {
  Statement stmt = null;
  try {
    flushStatements();
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameterObject, rowBounds, resultHandler, boundSql);
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    handler.parameterize(stmt);
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 8
Source Project: mybaties   Source File: SimpleExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    //新建一个StatementHandler
    //这里看到ResultHandler传入的是null
    StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
    //准备语句
    stmt = prepareStatement(handler, ms.getStatementLog());
    //StatementHandler.update
    return handler.update(stmt);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 9
Source Project: mybaties   Source File: SimpleExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    //新建一个StatementHandler
    //这里看到ResultHandler传入了
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    //准备语句
    stmt = prepareStatement(handler, ms.getStatementLog());
    //StatementHandler.query
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 10
Source Project: mybatis   Source File: ReuseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
  Statement stmt;
  //得到绑定的SQL语句
  BoundSql boundSql = handler.getBoundSql();
  String sql = boundSql.getSql();
  //如果缓存中已经有了,直接得到Statement
  if (hasStatementFor(sql)) {
    stmt = getStatement(sql);
  } else {
    //如果缓存没有找到,则和SimpleExecutor处理完全一样,然后加入缓存
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection);
    putStatement(sql, stmt);
  }
  handler.parameterize(stmt);
  return stmt;
}
 
Example 11
Source Project: mybatis   Source File: BatchExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  final Configuration configuration = ms.getConfiguration();
  final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  final BoundSql boundSql = handler.getBoundSql();
  final String sql = boundSql.getSql();
  final Statement stmt;
  if (sql.equals(currentSql) && ms.equals(currentStatement)) {
    int last = statementList.size() - 1;
    stmt = statementList.get(last);
    BatchResult batchResult = batchResultList.get(last);
    batchResult.addParameterObject(parameterObject);
  } else {
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    currentSql = sql;
    currentStatement = ms;
    statementList.add(stmt);
    batchResultList.add(new BatchResult(ms, sql, parameterObject));
  }
  handler.parameterize(stmt);
  handler.batch(stmt);
  return BATCH_UPDATE_RETURN_VALUE;
}
 
Example 12
Source Project: mybatis   Source File: BatchExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
    throws SQLException {
  Statement stmt = null;
  try {
    flushStatements();
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameterObject, rowBounds, resultHandler, boundSql);
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    handler.parameterize(stmt);
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 13
Source Project: mybatis   Source File: SimpleExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    //新建一个StatementHandler
    //这里看到ResultHandler传入的是null
    StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
    //准备语句
    stmt = prepareStatement(handler, ms.getStatementLog());
    //StatementHandler.update
    return handler.update(stmt);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 14
Source Project: mybatis   Source File: SimpleExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    //新建一个StatementHandler
    //这里看到ResultHandler传入了
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    //准备语句
    stmt = prepareStatement(handler, ms.getStatementLog());
    //StatementHandler.query
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 15
Source Project: QuickProject   Source File: PageInterceptor.java    License: 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();
	MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory());
	RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
	if ((rowBounds != null) && (rowBounds != RowBounds.DEFAULT)) {
           Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
           Dialect dialect = DialectParser.parse(configuration);
           String sql = (String) metaStatementHandler.getValue("delegate.boundSql.sql");
           sql = dialect.addLimitString(sql, rowBounds.getOffset(), rowBounds.getLimit());

           metaStatementHandler.setValue("delegate.boundSql.sql", sql);
           metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
           metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
	}

	log.debug("SQL : " + boundSql.getSql());
	return invocation.proceed();
}
 
Example 16
@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 17
/**
 * 生成拦截对象的代理
 *
 * @param target 目标对象
 * @return 代理对象
 */
@Override
public Object plugin(Object target) {
	if (target instanceof StatementHandler) {
		return Plugin.wrap(target, this);
	}
	return target;
}
 
Example 18
Source Project: seppb   Source File: PerformanceInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object target = invocation.getTarget();
	Stopwatch started = Stopwatch.createStarted();
	StatementHandler statementHandler = (StatementHandler) target;
	Object obj = invocation.proceed();
	long endTime = started.stop().elapsed(TimeUnit.MILLISECONDS);
	if (properties.getSlowTime() <= endTime) {
		BoundSql boundSql = statementHandler.getBoundSql();
		String sql = boundSql.getSql();
           mysqlSlowQuery.info("执行耗时:{} 毫秒[slowSql]{} ", endTime, sql);
	}
	return obj;
}
 
Example 19
Source Project: FEBS-Cloud   Source File: DataPermissionInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
    if (target instanceof StatementHandler) {
        return Plugin.wrap(target, this);
    }
    return target;
}
 
Example 20
Source Project: MeetingFilm   Source File: DataScopeInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) PluginUtils.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 = CollectionKit.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 21
Source Project: code   Source File: DataScopeInterceptor.java    License: 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 22
Source Project: pre   Source File: DataScopeInterceptor.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 生成拦截对象的代理
 *
 * @param target 目标对象
 * @return 代理对象
 */
@Override
public Object plugin(Object target) {
    if (target instanceof StatementHandler) {
        return Plugin.wrap(target, this);
    }
    return target;
}
 
Example 23
Source Project: Aooms   Source File: PagingInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {

        /*MappedStatement mappedStatement2 = (MappedStatement)invocation.getArgs()[0];
        if(MyBatisConst.MS_RECORD_FIND_BY_PK.equals(mappedStatement2.getId())){
            System.err.println("invocation = " + invocation);
        }else{
            return invocation.proceed();
        }*/

        StatementHandler target = MetaObjectAssistant.getTarget(invocation,StatementHandler.class);
        MetaObject metaObject = MetaObjectAssistant.getMetaObject(target);

        PreparedStatementHandler preparedStatementHandler = (PreparedStatementHandler) metaObject.getValue("delegate");
        Map para = (Map) preparedStatementHandler.getBoundSql().getParameterObject();
        if(para == null) return invocation.proceed();

        Object isCount = para.get(MyBatisConst.CRUD_QUERY_COUNT_PLACEHOLDER);
        Object isPaging = para.get(MyBatisConst.CRUD_QUERY_PAGING_PLACEHOLDER);

        if(isCount != null){
            String countsql = "select count(*) count from (" + preparedStatementHandler.getBoundSql().getSql() + ") _table";
            metaObject.setValue("delegate.boundSql.sql",countsql);
        }

        if(isPaging != null){
            String ds = DynamicDataSourceHolder.getDataSource();
            String driveClass = Aooms.self().getDynamicDataSource().getDriveName(ds == null ? AoomsVar.DEFAULT_DATASOURCE : ds);
            //(String)metaObject.getValue("delegate.configuration.environment.dataSource.driverClass");
            RowBounds rowBounds = (RowBounds) metaObject.getValue("delegate.rowBounds");
            String sql = preparedStatementHandler.getBoundSql().getSql();
            String pagingSql = dialectSelector.selector(driveClass).pagingQuery(sql,rowBounds);
            metaObject.setValue("delegate.boundSql.sql",pagingSql);

            metaObject.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET); // 默认分页不生效
            metaObject.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);   // 默认分页不生效
        }

        Object value = invocation.proceed();
        return value;
    }
 
Example 24
Source Project: mybatis-boost   Source File: MetricInterceptor.java    License: 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 25
Source Project: ssm-demo   Source File: PageInterceptor.java    License: 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 26
Source Project: pig   Source File: DataScopeInterceptor.java    License: 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 27
Source Project: pig   Source File: DataScopeInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * 生成拦截对象的代理
 *
 * @param target 目标对象
 * @return 代理对象
 */
@Override
public Object plugin(Object target) {
    if (target instanceof StatementHandler) {
        return Plugin.wrap(target, this);
    }
    return target;
}
 
Example 28
@Override
public Object plugin(Object target) {
	if (target instanceof StatementHandler) {
		return Plugin.wrap(target, this);
	}
	return target;
}
 
Example 29
/**
 * 生成拦截对象的代理
 *
 * @param target 目标对象
 * @return 代理对象
 */
@Override
public Object plugin(Object target) {
	if (target instanceof StatementHandler) {
		return Plugin.wrap(target, this);
	}
	return target;
}
 
Example 30
Source Project: mybatis.flying   Source File: AutoMapperInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
	if (target instanceof StatementHandler) {
		return Plugin.wrap(target, this);
	} else {
		return target;
	}
}