org.apache.ibatis.mapping.BoundSql Java Examples

The following examples show how to use org.apache.ibatis.mapping.BoundSql. 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: ExecutorUtil.java    From Mybatis-PageHelper with 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 #2
Source File: PaginationInterceptor.java    From platform with 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 #3
Source File: BaseExecutor.java    From mybatis with 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 #4
Source File: HerdDBDialect.java    From Mybatis-PageHelper with 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 #5
Source File: HaloInterceptor.java    From Milkomeda with 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 #6
Source File: BatchExecutor.java    From mybaties with 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 #7
Source File: CheckSQLInterceptor.java    From java-tutorial with 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 #8
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 #9
Source File: BaseExecutor.java    From mybaties with 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 #10
Source File: DynamicSqlSourceTest.java    From mybaties with 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 #11
Source File: CachingExecutor.java    From mybatis with 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 #12
Source File: UpdateEnhancement.java    From mybatis-boost with 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 #13
Source File: SqlHelper.java    From mybatis-paging with 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 #14
Source File: MapperSqlProvider.java    From mybatis-boost with 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 #15
Source File: DynamicSqlSourceTest.java    From mybatis with 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 #16
Source File: DynamicSqlSourceTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimWHEREANDWithTABForFirstCondition() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE \t ID = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   and\t ID = ?  ")), "true"
              )
          )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example #17
Source File: SelectOrCountAll.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String tableName = EntityUtils.getTableName(MapperUtils.getEntityTypeFromMapper
                    (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.'))),
            configuration.getNameAdaptor());
    metaObject.setValue("delegate.boundSql.sql", (mappedStatement.getId().endsWith("countAll") ?
            "SELECT COUNT(*) FROM " : "SELECT * FROM ") + tableName);
}
 
Example #18
Source File: VelocitySqlSource.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public BoundSql getBoundSql(Object parameterObject) {
  Map<String, Object> bindings = createBindings(parameterObject, configuration);
  VelocityContext context = new VelocityContext(bindings);
  StringWriter sw = new StringWriter();
  script.merge(context, sw);
  VelocitySqlSourceBuilder sqlSourceParser = new VelocitySqlSourceBuilder(configuration);
  Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
  SqlSource sqlSource = sqlSourceParser.parse(sw.toString(), parameterType);
  BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
  for (Map.Entry<String, Object> entry : bindings.entrySet()) {
    boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
  }
  return boundSql;

}
 
Example #19
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private Object getNestedQueryConstructorValue(ResultSet rs, ResultMapping constructorMapping, String columnPrefix) throws SQLException {
  final String nestedQueryId = constructorMapping.getNestedQueryId();
  final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
  final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
  final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, constructorMapping, nestedQueryParameterType, columnPrefix);
  Object value = null;
  if (nestedQueryParameterObject != null) {
    final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
    final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT, nestedBoundSql);
    final Class<?> targetType = constructorMapping.getJavaType();
    final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery, nestedQueryParameterObject, targetType, key, nestedBoundSql);
    value = resultLoader.loadResult();
  }
  return value;
}
 
Example #20
Source File: InsertEnhancement.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    String sqlUpperCase = sql.toUpperCase();
    if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT &&
            !sqlUpperCase.startsWith("INSERT INTO ") && sqlUpperCase.startsWith("INSERT ")) {
        Matcher matcher = PATTERN_LITERAL_COLUMNS.matcher(sql = sql.substring(7));
        if (!matcher.find()) {
            throw new IllegalStateException("Found INSERT statement but no column is specified");
        }

        String literalColumns = matcher.group();
        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(literalColumns, entityType, mapUnderscoreToCamelCase);

        List<?> entities = boundSql.getParameterObject() instanceof Map ?
                (List<?>) ((Map) boundSql.getParameterObject()).get("param1") :
                Collections.singletonList(Objects.requireNonNull(boundSql.getParameterObject(),
                        "ParameterObject mustn't be null"));
        if (entities.isEmpty()) {
            throw new IllegalArgumentException("Can't insert empty list");
        } else {
            String additionalStatement = sql.substring(literalColumns.length());
            org.apache.ibatis.session.Configuration configuration =
                    (org.apache.ibatis.session.Configuration) metaObject.getValue("delegate.configuration");
            Object parameterObject = buildParameterObject(entities);
            metaObject.setValue("delegate.boundSql.sql",
                    buildSql(entityType, propertiesAndColumns.second(), entities.size(), additionalStatement));
            metaObject.setValue("delegate.boundSql.parameterMappings",
                    MyBatisUtils.getListParameterMappings(configuration, propertiesAndColumns.first(), entities.size()));
            metaObject.setValue("delegate.boundSql.parameterObject", parameterObject);
            MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
                    .setValue("parameterObject", parameterObject);
        }
    }
}
 
Example #21
Source File: SqlStatementInterceptor.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object returnValue;
    long start = System.currentTimeMillis();
    // 执行 SQL语句
    returnValue = invocation.proceed();
    long end = System.currentTimeMillis();
    // 耗时
    long time = end - start;
    try {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = null;
        //获取参数,if语句成立,表示sql语句有参数,参数格式是map形式
        if (args.length > 1)
            parameter = invocation.getArgs()[1];
        // 获取到节点的 id,即 sql语句的 id
        String sqlId = ms.getId();
        // BoundSql就是封装 MyBatis最终产生的 sql类
        BoundSql boundSql = ms.getBoundSql(parameter);
        // 获取节点的配置
        Configuration configuration = ms.getConfiguration();
        // 获取到最终的 sql语句
        printSql(configuration, boundSql, sqlId, time);
    } catch (Exception e) {
        logger.error("sql拦截异常:{} ", e.getMessage());
    }
    return returnValue;
}
 
Example #22
Source File: DispatcherInterceptor.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Connection connection = (Connection) invocation.getArgs()[0];
    MetaObject metaObject = MyBatisUtils.getMetaObject(invocation.getTarget());
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    preprocessors.forEach(p -> p.replace(connection, metaObject, mappedStatement, boundSql));
    providers.forEach(p -> p.replace(connection, metaObject, mappedStatement, boundSql));
    return invocation.proceed();
}
 
Example #23
Source File: DynamicSqlSourceTest.java    From mybatis with 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 #24
Source File: SQLHelper.java    From Shop-for-JavaWeb with 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 #25
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 5 votes vote down vote up
/**
 * 获取sql语句
 * @param invocation
 * @return
 */
private String getSqlByInvocation(Invocation invocation) {
    final Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    Object parameterObject = args[1];
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    return boundSql.getSql();
}
 
Example #26
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    // 拦截sql
    Object[] args = invocation.getArgs();
    MappedStatement statement = (MappedStatement) args[0];
    Object parameterObject = args[1];
    BoundSql boundSql = statement.getBoundSql(parameterObject);
    String sql = boundSql.getSql();
    LOGGER.info("获取到的SQL:{}"+sql);
    if (StringUtils.isBlank(sql)) {
        return invocation.proceed();
    }
    // 返回
    return invocation.proceed();
}
 
Example #27
Source File: Db2Dialect.java    From Mybatis-PageHelper with 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;
}
 
Example #28
Source File: RecordUpdate.java    From Aooms with 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 #29
Source File: MySQL.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    metaObject.setValue("delegate.boundSql.sql",
            SqlUtils.appendLimit(boundSql.getSql(), (RowBounds) metaObject.getValue("delegate.rowBounds")));
    metaObject.setValue("delegate.rowBounds", RowBounds.DEFAULT);
    MyBatisUtils.getMetaObject(metaObject.getValue("delegate.resultSetHandler"))
            .setValue("rowBounds", RowBounds.DEFAULT);
}
 
Example #30
Source File: DynamicSqlSourceTest.java    From mybaties with 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());
}