Java Code Examples for org.apache.ibatis.mapping.BoundSql

The following examples show how to use org.apache.ibatis.mapping.BoundSql. 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: mybatis   Source File: BaseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  List<E> list;
  //先向缓存中放入占位符???
  localCache.putObject(key, EXECUTION_PLACEHOLDER);
  try {
    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
  } finally {
    //最后删除占位符
    localCache.removeObject(key);
  }
  //加入缓存
  localCache.putObject(key, list);
  //如果是存储过程,OUT参数也加入缓存
  if (ms.getStatementType() == StatementType.CALLABLE) {
    localOutputParameterCache.putObject(key, parameter);
  }
  return list;
}
 
Example 2
Source Project: Milkomeda   Source File: HaloInterceptor.java    License: MIT License 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    // 获取第一个参数,MappedStatement
    MappedStatement mappedStatement = (MappedStatement) args[0];
    // 获取第二个参数,该参数类型根据Mapper方法的参数决定,如果是一个参数,则为实体或简单数据类型;如果是多个参数,则为Map。
    Object param = args.length > 1 ? args[1] : null;
    BoundSql boundSql = mappedStatement.getSqlSource().getBoundSql(param);
    String sql = WHITE_SPACE_BLOCK_PATTERN.matcher(boundSql.getSql()).replaceAll(" ");
    if (!props.isShowSlowLog()) {
        return warpIntercept(invocation, mappedStatement, sql, param);
    }
    long start = System.currentTimeMillis();
    Object result = warpIntercept(invocation, mappedStatement, sql, param);
    long end = System.currentTimeMillis();
    long time = end - start;
    if (time > props.getSlowThreshold().toMillis()) {
        logSqlInfo(mappedStatement.getConfiguration(), boundSql, sql, mappedStatement.getId(), time);
    }
    return result;
}
 
Example 3
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 4
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 5
Source Project: mybaties   Source File: BaseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  List<E> list;
  //先向缓存中放入占位符???
  localCache.putObject(key, EXECUTION_PLACEHOLDER);
  try {
    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
  } finally {
    //最后删除占位符
    localCache.removeObject(key);
  }
  //加入缓存
  localCache.putObject(key, list);
  //如果是存储过程,OUT参数也加入缓存
  if (ms.getStatementType() == StatementType.CALLABLE) {
    localOutputParameterCache.putObject(key, parameter);
  }
  return list;
}
 
Example 6
Source Project: mybaties   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPerformStrictMatchOnForEachVariableSubstitution() throws Exception {
  final Map<String, Object> param = new HashMap<String, Object>();
  final Map<String, String> uuu = new HashMap<String, String>();
  uuu.put("u", "xyz");
  List<Bean> uuuu = new ArrayList<Bean>();
  uuuu.add(new Bean("bean id"));
  param.put("uuu", uuu);
  param.put("uuuu", uuuu);
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("INSERT INTO BLOG (ID, NAME, NOTE, COMMENT) VALUES"),
      new ForEachSqlNode(new Configuration(),mixedContents(
          new TextSqlNode("#{uuu.u}, #{u.id}, #{ u,typeHandler=org.apache.ibatis.type.StringTypeHandler},"
              + " #{u:VARCHAR,typeHandler=org.apache.ibatis.type.StringTypeHandler}")), "uuuu", "uu", "u", "(", ")", ","));
  BoundSql boundSql = source.getBoundSql(param);
  assertEquals(4, boundSql.getParameterMappings().size());
  assertEquals("uuu.u", boundSql.getParameterMappings().get(0).getProperty());
  assertEquals("__frch_u_0.id", boundSql.getParameterMappings().get(1).getProperty());
  assertEquals("__frch_u_0", boundSql.getParameterMappings().get(2).getProperty());
  assertEquals("__frch_u_0", boundSql.getParameterMappings().get(3).getProperty());
}
 
Example 7
Source Project: mybatis   Source File: CachingExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
    throws SQLException {
  Cache cache = ms.getCache();
  //默认情况下是没有开启缓存的(二级缓存).要开启二级缓存,你需要在你的 SQL 映射文件中添加一行: <cache/>
  //简单的说,就是先查CacheKey,查不到再委托给实际的执行器去查
  if (cache != null) {
    flushCacheIfRequired(ms);
    if (ms.isUseCache() && resultHandler == null) {
      ensureNoOutParams(ms, parameterObject, boundSql);
      @SuppressWarnings("unchecked")
      List<E> list = (List<E>) tcm.getObject(cache, key);
      if (list == null) {
        list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
        tcm.putObject(cache, key, list); // issue #578 and #116
      }
      return list;
    }
  }
  return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
 
Example 8
Source Project: mybatis-boost   Source File: UpdateEnhancement.java    License: MIT License 6 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    if (mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE &&
            sql.toUpperCase().startsWith("UPDATE SET ")) {
        String[] split = splitSql(sql); // split[0] = columns, split[1] = conditions(if there were)
        Class<?> entityType = MapperUtils.getEntityTypeFromMapper
                (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");

        BinaryTuple<List<String>, List<String>> propertiesAndColumns =
                SqlUtils.getPropertiesAndColumnsFromLiteralColumns(split[0], entityType, mapUnderscoreToCamelCase);
        List<String> conditionProperties = getConditionProperties(entityType, boundSql.getParameterMappings());
        propertiesAndColumns.first().removeAll(conditionProperties);
        propertiesAndColumns.second().removeAll(conditionProperties.stream()
                .map(it -> SqlUtils.normalizeColumn(it, mapUnderscoreToCamelCase)).collect(Collectors.toList()));

        metaObject.setValue("delegate.boundSql.sql",
                buildSQL(sql, entityType, propertiesAndColumns.second(), split));
        metaObject.setValue("delegate.boundSql.parameterMappings",
                getParameterMappings(metaObject, boundSql, propertiesAndColumns.first()));
    }
}
 
Example 9
Source Project: mybatis-paging   Source File: SqlHelper.java    License: MIT License 6 votes vote down vote up
public static int getCount(final MappedStatement ms, final Connection connection,
                           final Object parameterObject, Dialect dialect) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    String countSql = dialect.getCountString(boundSql.getSql());

    logger.debug("Total count SQL [{}]", countSql);
    logger.debug("Parameters: {} ", parameterObject);

    PreparedStatement stmt = null;
    ResultSet rs;
    try{
        stmt = connection.prepareStatement(countSql);
        DefaultParameterHandler handler = new DefaultParameterHandler(ms, parameterObject, boundSql);
        handler.setParameters(stmt);
        rs = stmt.executeQuery();

        int count = 0;
        if(rs.next()){
            count = rs.getInt(1);
        }

        return count;
    }finally {
        closeStatement(stmt);
    }
}
 
Example 10
Source Project: mybatis-boost   Source File: MapperSqlProvider.java    License: MIT License 6 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    if (Objects.equals(boundSql.getSql(), SqlProvider.MYBATIS_BOOST)) {
        Class<?> providerType = (Class<?>)
                MyBatisUtils.getMetaObject(mappedStatement.getSqlSource()).getValue("providerType");
        SqlProvider provider = providerMap.get(providerType);
        if (provider == null) {
            synchronized (providerType) {
                provider = providerMap.computeIfAbsent(providerType, UncheckedFunction.of(k -> {
                    SqlProvider p = (SqlProvider) providerType.newInstance();
                    if (p instanceof ConfigurationAware) {
                        ((ConfigurationAware) p).setConfiguration(configuration);
                    }
                    return p;
                }));
            }
        }
        if (provider != null) {
            provider.replace(connection, metaObject, mappedStatement, boundSql);
        }
    }
}
 
Example 11
Source Project: Mybatis-PageHelper   Source File: ExecutorUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 分页查询
 *
 * @param dialect
 * @param executor
 * @param ms
 * @param parameter
 * @param rowBounds
 * @param resultHandler
 * @param boundSql
 * @param cacheKey
 * @param <E>
 * @return
 * @throws SQLException
 */
public static  <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter,
                             RowBounds rowBounds, ResultHandler resultHandler,
                             BoundSql boundSql, CacheKey cacheKey) throws SQLException {
    //判断是否需要进行分页查询
    if (dialect.beforePage(ms, parameter, rowBounds)) {
        //生成分页的缓存 key
        CacheKey pageKey = cacheKey;
        //处理参数对象
        parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
        //调用方言获取分页 sql
        String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
        BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);

        Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
        //设置动态参数
        for (String key : additionalParameters.keySet()) {
            pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
        }
        //执行分页查询
        return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
    } else {
        //不执行分页的情况下,也不执行内存分页
        return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
    }
}
 
Example 12
Source Project: java-tutorial   Source File: CheckSQLInterceptor.java    License: MIT License 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

    //获取方法的第0个参数,也就是MappedStatement。@Signature注解中的args中的顺序
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    //获取sql命令操作类型
    SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
    final Object[] queryArgs = invocation.getArgs();
    final Object parameter = queryArgs[1];

    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    String sql = boundSql.getSql();

    if (SqlCommandType.DELETE.equals(sqlCommandType)) {
        //格式化sql
        sql = sql.replace("\n", "");
        if (!sql.toLowerCase().contains(SQL_DELETE_WHERE)) {
            sql = sql.replace(" ", "");
            logger.warn("删除语句中没有where条件,sql为:{}", sql);
            throw new SQLException("删除语句中没有where条件");
        }
        return invocation.proceed();
    }

    return null;
}
 
Example 13
Source Project: platform   Source File: PaginationInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 查询总记录条数
 *
 * @param sql             SQL
 * @param mappedStatement {@link MappedStatement}
 * @param boundSql        {@link BoundSql}
 * @param connection      {@link Connection}
 */
protected long queryTotal(String sql, MappedStatement mappedStatement, BoundSql boundSql, Connection connection) {
    long total = 0;
    try (PreparedStatement statement = connection.prepareStatement(sql)) {
        DefaultParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql);
        parameterHandler.setParameters(statement);
        try (ResultSet resultSet = statement.executeQuery()) {
            if (resultSet.next()) {
                total = resultSet.getLong(1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return total;
}
 
Example 14
Source Project: Mybatis-PageHelper   Source File: HerdDBDialect.java    License: MIT License 6 votes vote down vote up
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
    paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
    paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
    pageKey.update(page.getStartRow());
    pageKey.update(page.getPageSize());
    if (boundSql.getParameterMappings() != null) {
        List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
        if (page.getStartRow() == 0) {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        } else {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class).build());
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        }
        MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
        metaObject.setValue("parameterMappings", newParameterMappings);
    }
    return paramMap;
}
 
Example 15
Source Project: mybatis   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConditionallyDefault() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE CATEGORY = 'DEFAULT'";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new ChooseSqlNode(new ArrayList<SqlNode>() {{
        add(new IfSqlNode(mixedContents(new TextSqlNode("WHERE CATEGORY = ?")), "false"
        ));
        add(new IfSqlNode(mixedContents(new TextSqlNode("WHERE CATEGORY = 'NONE'")), "false"
        ));
      }}, mixedContents(new TextSqlNode("WHERE CATEGORY = 'DEFAULT'"))));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 16
Source Project: mybatis   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimNoWhereClause() throws Exception {
  final String expected = "SELECT * FROM BLOG";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   and ID = ?   ")), "false"
          ),
          new IfSqlNode(mixedContents(new TextSqlNode("OR NAME = ?  ")), "false"
          )
      )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 17
Source Project: mybaties   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimWHEREInsteadOfANDForBothConditions() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE  ID = ?   OR NAME = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   and ID = ?   ")), "true"
          ),
          new IfSqlNode(mixedContents(new TextSqlNode("OR NAME = ?  ")), "true"
          )
      )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 18
Source Project: Shop-for-JavaWeb   Source File: SQLHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
 *
 * @param ps              表示预编译的 SQL 语句的对象。
 * @param mappedStatement MappedStatement
 * @param boundSql        SQL
 * @param parameterObject 参数对象
 * @throws java.sql.SQLException 数据库异常
 */
@SuppressWarnings("unchecked")
public static void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
        Configuration configuration = mappedStatement.getConfiguration();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        MetaObject metaObject = parameterObject == null ? null :
                configuration.newMetaObject(parameterObject);
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                if (parameterObject == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) {
                    value = boundSql.getAdditionalParameter(prop.getName());
                    if (value != null) {
                        value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                    }
                } else {
                    value = metaObject == null ? null : metaObject.getValue(propertyName);
                }
                @SuppressWarnings("rawtypes")
	TypeHandler typeHandler = parameterMapping.getTypeHandler();
                if (typeHandler == null) {
                    throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                }
                typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
            }
        }
    }
}
 
Example 19
Source Project: mybaties   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimSETInsteadOfCOMMAForBothConditions() throws Exception {
  final String expected = "UPDATE BLOG SET ID = ?,  NAME = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("UPDATE BLOG"),
      new SetSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode(" ID = ?, ")), "true"
          ),
          new IfSqlNode(mixedContents(new TextSqlNode(" NAME = ?, ")), "true"
          )
      )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 20
Source Project: mybaties   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDemonstrateMultipartExpectedTextWithNoLoopsOrConditionals() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE ID = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new TextSqlNode("WHERE ID = ?"));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 21
Source Project: Mybatis-PageHelper   Source File: AbstractHelperDialect.java    License: MIT License 5 votes vote down vote up
@Override
public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
    Page<Object> page = getLocalPage();
    String countColumn = page.getCountColumn();
    if (StringUtil.isNotEmpty(countColumn)) {
        return countSqlParser.getSmartCountSql(boundSql.getSql(), countColumn);
    }
    return countSqlParser.getSmartCountSql(boundSql.getSql());
}
 
Example 22
Source Project: mybatis   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimWHEREANDWithCRLFForFirstCondition() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE \r\n ID = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   and\r\n ID = ?  ")), "true"
              )
          )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 23
Source Project: mybaties   Source File: DefaultParameterHandler.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
  this.mappedStatement = mappedStatement;
  this.configuration = mappedStatement.getConfiguration();
  this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
  this.parameterObject = parameterObject;
  this.boundSql = boundSql;
}
 
Example 24
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 25
Source Project: AsuraFramework   Source File: OffsetLimitInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private BoundSql copyFromBoundSql(MappedStatement ms, BoundSql boundSql,
		String sql, List<ParameterMapping> parameterMappings,Object parameter) {
	BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),sql, parameterMappings, parameter);
	for (ParameterMapping mapping : boundSql.getParameterMappings()) {
	    String prop = mapping.getProperty();
	    if (boundSql.hasAdditionalParameter(prop)) {
	        newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
	    }
	}
	return newBoundSql;
}
 
Example 26
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 27
Source Project: DDMQ   Source File: MybatisInterceptor.java    License: 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 28
Source Project: Aooms   Source File: RecordInsert.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process() {
    MappedStatement mappedStatement = MetaObjectAssistant.getMappedStatement(metaObject);
    Object parameterObject = MetaObjectAssistant.getParameterObject(metaObject);
    Record record = (Record) parameterObject;
    String tableName = record.getGeneral(MyBatisConst.TABLE_NAME_PLACEHOLDER);
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(" insert into ");
    stringBuilder.append(tableName); // tableName
    stringBuilder.append(" ({}) ");
    stringBuilder.append(" values ");
    stringBuilder.append(" ({}) ");

    StringBuilder columns = new StringBuilder();
    StringBuilder values = new StringBuilder();

    int index = 0;
    Iterator<String> keyIterator = record.keySet().iterator();
    while (keyIterator.hasNext()) {
        String key = keyIterator.next();
        if (index > 0) {
            columns.append(",");
            values.append(",");
        }
        columns.append(key);
        values.append("#{").append(key).append("}");
        index++;
    }

    String sql = StrUtil.format(stringBuilder, columns, values);
    Configuration configuration = MetaObjectAssistant.getConfiguration(metaObject);
    SqlSource sqlSource = configuration.getLanguageRegistry().getDefaultDriver().createSqlSource(mappedStatement.getConfiguration(), sql, Map.class);
    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
    //metaObject.setValue("delegate.boundSql", boundSql);
    //metaObject.setValue("delegate.parameterHandler.boundSql", boundSql);

    MetaObjectAssistant.setDelegateBoundSql(metaObject,boundSql);
    MetaObjectAssistant.setDelegateParameterHandlerBoundSql(metaObject,boundSql);
}
 
Example 29
Source Project: Aooms   Source File: RecordUpdate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process() {
    MappedStatement mappedStatement = MetaObjectAssistant.getMappedStatement(metaObject);
    Object parameterObject = MetaObjectAssistant.getParameterObject(metaObject);
    Record record = (Record) parameterObject;

    String tableName = record.getGeneral(MyBatisConst.TABLE_NAME_PLACEHOLDER);
    String pkName = String.valueOf(record.getOrDefault(MyBatisConst.TABLE_PK_NAME_PLACEHOLDER, AoomsVar.ID));
    Object pkValue = record.get(pkName);

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(" update ");
    stringBuilder.append(tableName); // tableName
    stringBuilder.append(" set {} ");
    stringBuilder.append(" where "+ pkName +" = #{"+ pkName +"} ");

    StringBuilder columns = new StringBuilder();
    int index = 0;
    Iterator<String> keyIterator = record.keySet().iterator();
    while (keyIterator.hasNext()) {
        String key = keyIterator.next();
        if (index > 0) {
            columns.append(",");
        }
        columns.append(key).append(" = ").append("#{").append(key).append("}");
        index++;
    }

    String sql = StrUtil.format(stringBuilder, columns);
    //SqlSource sqlSource = new XMLLanguageDriver().createSqlSource(mappedStatement.getConfiguration(), sql, Map.class);
    Configuration configuration = MetaObjectAssistant.getConfiguration(metaObject);
    SqlSource sqlSource = configuration.getLanguageRegistry().getDefaultDriver().createSqlSource(mappedStatement.getConfiguration(), sql, Map.class);
    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);

    MetaObjectAssistant.setDelegateBoundSql(metaObject,boundSql);
    MetaObjectAssistant.setDelegateParameterHandlerBoundSql(metaObject,boundSql);
}
 
Example 30
Source Project: Mybatis-PageHelper   Source File: Db2Dialect.java    License: MIT License 5 votes vote down vote up
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
    paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow() + 1);
    paramMap.put(PAGEPARAMETER_SECOND, page.getEndRow());
    //处理pageKey
    pageKey.update(page.getStartRow() + 1);
    pageKey.update(page.getEndRow());
    //处理参数配置
    handleParameter(boundSql, ms);
    return paramMap;
}