Java Code Examples for org.apache.ibatis.executor.statement.StatementHandler#getBoundSql()

The following examples show how to use org.apache.ibatis.executor.statement.StatementHandler#getBoundSql() . 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: 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 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: ReuseExecutor.java    From mybaties with 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 4
Source File: BatchExecutor.java    From mybaties with 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 5
Source File: ReuseExecutor.java    From mybatis with 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 File: BatchExecutor.java    From mybatis with 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 File: PageInterceptor.java    From QuickProject 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();
	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 8
Source File: PerformanceInterceptor.java    From seppb with 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 9
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 10
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 11
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();
}
 
Example 12
Source File: SQLRouterInterceptor.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
	Object result = null;

	if (invocation.getTarget() instanceof RoutingStatementHandler) {
		RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
		StatementHandler delegate = (StatementHandler) ReflectionUtil.getFieldValue(statementHandler, "delegate");
		BoundSql boundSql = delegate.getBoundSql();

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

		// 1、 如果前端有指定路由则,优先采用指定的路由
		if (RouterContext.containsKey(RouterConsts.ROUTER_KEY) && !hasAnnotation(sql)) {
			RouterInfo routerInfo = RouterContext.get(RouterConsts.ROUTER_KEY);
			sql = new StringBuilder(routerInfo.getSqlrouter()).append(sql).toString();

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

		// 2、如果没有路由信息,对只读事物添加读取从库的路由
		if (!hasAnnotation(sql) && connection.isReadOnly()) {

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

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

		result = invocation.proceed();

		// if (isDML(sql) &&
		// !RouterContext.containsKey(RouterConsts.ROUTER_KEY)) {
		// 如果更改执行的是DML语句,则设置后续的CRUD路由到master
		// String appName = PropertiesUtil.get("app.name");
		// //TODO这里可能需要针对应用来进行主从路由,存在一条链路路由到多个应用的不同DB中
		// RouterContext.put(RouterConsts.ROUTER_KEY,
		// msHint.getRouteMasterHint());
		// }

	} else {
		result = invocation.proceed();
	}

	return result;
}
 
Example 13
Source File: TableShardInterceptor.java    From mybatis-shard with Eclipse Public License 1.0 3 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {

        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();

        BoundSql boundSql = statementHandler.getBoundSql();

        String sql = tryConvertSql(boundSql);

        if (StringUtils.isNotEmpty(sql)) {
            Reflections.setFieldValue(boundSql, "sql", sql);
        }

        return invocation.proceed();

    }