Example usage for org.apache.ibatis.mapping BoundSql getSql

List of usage examples for org.apache.ibatis.mapping BoundSql getSql

Introduction

In this page you can find the example usage for org.apache.ibatis.mapping BoundSql getSql.

Prototype

public String getSql() 

Source Link

Usage

From source file:com.luxoft.mybatis.splitter.ReusingBatchExecutor.java

License:Apache License

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();
    PreparedStatementKey key = new PreparedStatementKey(boundSql.getSql(), ms);
    StatementData statementData = statementsData.get(key);
    if (retainExecuteOrder && statementData != null && !key.equals(lastKey)) {
        statementData = null;/*w w w  . j  av a  2 s . c  o m*/
        executeUpTo(key, true);
    }
    if (statementData == null) {
        statementData = unusedStatementData.remove(key);
        if (statementData == null) {
            Connection connection = getConnection(ms.getStatementLog());
            Statement stmt = handler.prepare(connection);
            statementData = new StatementData(stmt);
        }
        statementsData.put(key, statementData);
    }
    lastKey = key;
    statementData.addParameterObject(parameterObject);
    handler.parameterize(statementData.getStatement());
    handler.batch(statementData.getStatement());
    return BATCH_UPDATE_RETURN_VALUE;
}

From source file:com.luxoft.mybatis.splitter.UpdateSplitterPlugin.java

License:Apache License

@Override
public Object intercept(Invocation invocation) throws Throwable {
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    Object parameterObject = invocation.getArgs()[1];
    final Configuration configuration = ms.getConfiguration();
    final StatementHandler handler = configuration.newStatementHandler((Executor) invocation.getTarget(), ms,
            parameterObject, RowBounds.DEFAULT, null, null);
    final BoundSql boundSql = handler.getBoundSql();
    final String sql = boundSql.getSql();
    List<String> splitted = splitter.split(sql);
    int rc = 0;/*from   w ww . ja va  2  s.  co m*/
    List<ParameterMapping> fullParameterMappings = new ArrayList<ParameterMapping>(
            boundSql.getParameterMappings());
    for (String sqlPart : splitted) {
        if (skipEmptyStatements && sqlPart.length() == 0) {
            continue;
        }
        int numParams = 0;
        for (int index = sqlPart.indexOf('?'); index >= 0; index = sqlPart.indexOf('?', index + 1)) {
            numParams++;
        }
        MappedStatement subStatement = subStatements.get(ms);
        if (subStatement == null) {
            subStatement = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(),
                    new SwitchingSqlSource(configuration), ms.getSqlCommandType()).cache(ms.getCache())
                            .databaseId(ms.getDatabaseId()).fetchSize(ms.getFetchSize())
                            .timeout(ms.getTimeout()).flushCacheRequired(ms.isFlushCacheRequired())
                            .useCache(ms.isUseCache()).build();
            subStatements.put(ms, subStatement);
        }
        List<ParameterMapping> subParameterMappings = fullParameterMappings.subList(0, numParams);
        ((SwitchingSqlSource) subStatement.getSqlSource()).switchParams(sqlPart, boundSql,
                new ArrayList<ParameterMapping>(subParameterMappings));
        subParameterMappings.clear();
        int subRc = (Integer) invocation.getMethod().invoke(invocation.getTarget(), subStatement,
                parameterObject);
        if (rc >= 0) {
            rc = subRc < 0 ? subRc : rc + subRc;
        }
    }
    return rc;
}

From source file:com.monee1988.core.mybatis.pageinterceptor.PageInterceptor.java

License:Open Source License

void processMybatisIntercept(final Object[] queryArgs, Invocation invocation) {
    MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
    Object parameter = queryArgs[PARAMETER_INDEX];

    Page<?> page = null;// w  w w. j ava  2s  .  c o  m

    if (parameter != null) {
        page = convertParameter(page, parameter);
    }

    if (dialect.supportsLimit() && page != null) {

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

        final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];
        int offset = rowBounds.getOffset();
        int limit = rowBounds.getLimit();
        offset = page.getOffset();
        limit = page.getPageSize();

        CachingExecutor executor = (CachingExecutor) invocation.getTarget();

        Transaction transaction = executor.getTransaction();
        try {
            Connection connection = transaction.getConnection();
            /**
             * 
             */
            this.setTotalRecord(page, ms, connection, parameter);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (dialect.supportsLimitOffset()) {

            sql = dialect.getLimitString(sql, offset, limit);
            offset = RowBounds.NO_ROW_OFFSET;

        } else {

            sql = dialect.getLimitString(sql, 0, limit);

        }
        limit = RowBounds.NO_ROW_LIMIT;

        queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit);

        BoundSql newBoundSql = copyFromBoundSql(ms, boundSql, sql);

        MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));

        queryArgs[MAPPED_STATEMENT_INDEX] = newMs;

    }
}

From source file:com.monee1988.core.mybatis.pageinterceptor.PageInterceptor.java

License:Open Source License

/**
 *
 * @param page/*w  w  w  . ja va 2  s. c  o  m*/
 * @param mappedStatement
 * @param connection
 * @param parameterObject
  */
private void setTotalRecord(Page<?> page, MappedStatement mappedStatement, Connection connection,
        Object parameterObject) {

    BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
    String sql = boundSql.getSql();
    String countSql = removeBreakingWhitespace(this.getCountSql(sql));
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, parameterMappings,
            parameterObject);
    ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject,
            countBoundSql);
    PreparedStatement pstmt = null;
    ResultSet rs = null;

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

    try {
        pstmt = connection.prepareStatement(countSql);
        parameterHandler.setParameters(pstmt);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            int totalRecord = rs.getInt(1);
            logger.debug("Total count: {}", totalRecord);
            page.setTotalCount(totalRecord);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.mybatisX.plugins.PaginationInterceptor.java

License:Apache License

public Object intercept(Invocation invocation) throws Throwable {

    Object target = invocation.getTarget();
    if (target instanceof StatementHandler) {
        StatementHandler statementHandler = (StatementHandler) target;
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
        RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");

        /* ??? */
        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }//from ww w.j a  v  a 2  s  .  c  om

        /* ? */
        IDialect dialect = getiDialect();

        /*
         * <p> ? </p> <p> ???????
         * </p>
         */
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        String originalSql = (String) boundSql.getSql();
        metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
        metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);

        /**
         * <p>
         * 
         * </p>
         * <p>
         *  count
         * </p>
         */
        if (rowBounds instanceof Pagination) {
            Pagination page = (Pagination) rowBounds;
            boolean orderBy = true;
            if (page.isSearchCount()) {
                /*
                 * COUNT  ORDER BY  SQL
                 */
                CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, page.isOptimizeCount());
                orderBy = countOptimize.isOrderBy();
            }
            /*  SQL */
            String buildSql = SqlUtils.concatOrderBy(originalSql, page, orderBy);
            originalSql = dialect.buildPaginationSql(buildSql, page.getOffsetCurrent(), page.getSize());
        }

        /**
         *  SQL 
         */
        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
    } else {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameterObject = null;
        RowBounds rowBounds = null;
        if (invocation.getArgs().length > 1) {
            parameterObject = invocation.getArgs()[1];
            rowBounds = (RowBounds) invocation.getArgs()[2];
        }
        /* ??? */
        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }

        BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
        /*
         * <p> ? </p> <p> ???????
         * </p>
         */
        String originalSql = (String) boundSql.getSql();

        /**
         * <p>
         * 
         * </p>
         * <p>
         *  count
         * </p>
         */
        if (rowBounds instanceof Pagination) {
            Connection connection = null;
            try {
                connection = mappedStatement.getConfiguration().getEnvironment().getDataSource()
                        .getConnection();
                Pagination page = (Pagination) rowBounds;
                if (page.isSearchCount()) {
                    /*
                     * COUNT  ORDER BY  SQL
                     */
                    CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql,
                            page.isOptimizeCount());
                    page = this.count(countOptimize.getCountSQL(), connection, mappedStatement, boundSql, page);
                    /**  0  */
                    if (page.getTotal() <= 0) {
                        return invocation.proceed();
                    }
                }
            } finally {
                IOUtils.closeQuietly(connection);
            }
        }
    }

    return invocation.proceed();

}

From source file:com.mybatisX.plugins.PerformanceInterceptor.java

License:Apache License

public Object intercept(Invocation invocation) throws Throwable {
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    Object parameterObject = null;
    if (invocation.getArgs().length > 1) {
        parameterObject = invocation.getArgs()[1];
    }/*from   w w  w .jav  a  2s .c o m*/

    String statementId = mappedStatement.getId();
    BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
    Configuration configuration = mappedStatement.getConfiguration();
    String sql = SqlUtils.sqlFormat(boundSql.getSql(), format);

    List<String> params = getParams(boundSql, parameterObject, configuration);

    long start = SystemClock.now();
    Object result = invocation.proceed();
    long end = SystemClock.now();
    long timing = end - start;
    System.err.println(" Time" + timing + " ms" + " - ID" + statementId + "\n SQL Params:"
            + params.toString() + "\n Execute SQL" + sql + "\n");
    if (maxTime >= 1 && timing > maxTime) {
        throw new MybatisXException(" The SQL execution time is too large, please optimize ! ");
    }
    return result;
}

From source file:com.mybatisX.plugins.SqlExplainInterceptor.java

License:Apache License

/**
 * <p>// ww  w  .jav  a2 s.  c  o m
 * ? SQL
 * </p>
 * 
 * @param configuration
 * @param mappedStatement
 * @param boundSql
 * @param connection
 * @param parameter
 * @return
 * @throws Exception
 */
protected void sqlExplain(Configuration configuration, MappedStatement mappedStatement, BoundSql boundSql,
        Connection connection, Object parameter) {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        StringBuilder explain = new StringBuilder("EXPLAIN ");
        explain.append(boundSql.getSql());
        String sqlExplain = explain.toString();
        StaticSqlSource sqlsource = new StaticSqlSource(configuration, sqlExplain,
                boundSql.getParameterMappings());
        MappedStatement.Builder builder = new MappedStatement.Builder(configuration, "explain_sql", sqlsource,
                SqlCommandType.SELECT);
        builder.resultMaps(mappedStatement.getResultMaps()).resultSetType(mappedStatement.getResultSetType())
                .statementType(mappedStatement.getStatementType());
        MappedStatement query_statement = builder.build();
        DefaultParameterHandler handler = new DefaultParameterHandler(query_statement, parameter, boundSql);
        stmt = connection.prepareStatement(sqlExplain);
        handler.setParameters(stmt);
        rs = stmt.executeQuery();
        while (rs.next()) {
            if (!"Using where".equals(rs.getString("Extra"))) {
                String tip = " Full table operation is prohibited. SQL: " + boundSql.getSql();
                if (this.isStopProceed()) {
                    throw new MybatisXException(tip);
                }
                logger.error(tip);
                break;
            }
        }

    } catch (Exception e) {
        throw new MybatisXException(e);
    } finally {
        IOUtils.closeQuietly(rs, stmt);
    }
}

From source file:com.navercorp.pinpoint.web.dao.ibatis.BindingLogPlugin32.java

License:Apache License

private void bindingLog(Invocation invocation) throws SQLException {

    Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    Object parameterObject = args[1];
    StatementType statementType = ms.getStatementType();
    if (StatementType.PREPARED == statementType || StatementType.CALLABLE == statementType) {
        Log statementLog = ms.getStatementLog();
        if (isDebugEnable(statementLog)) {
            BoundSql boundSql = ms.getBoundSql(parameterObject);

            String sql = boundSql.getSql();
            List<String> parameterList = getParameters(ms, parameterObject, boundSql);
            debug(statementLog, "==> BindingLog: " + bindLogFormatter.format(sql, parameterList));
        }/*  w ww  .  j av  a  2  s . co m*/
    }
}

From source file:com.saituo.talk.common.persistence.interceptor.PaginationInterceptor.java

License:Open Source License

@Override
public Object intercept(Invocation invocation) throws Throwable {

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

    // //?SQL//w  ww . ja v  a  2 s  .  c o  m
    // // if (mappedStatement.getId().matches(_SQL_PATTERN)) {
    // if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(),
    // _SQL_PATTERN) != -1) {
    Object parameter = invocation.getArgs()[1];
    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    Object parameterObject = boundSql.getParameterObject();

    // ??
    Page<Object> page = null;
    if (parameterObject != null) {
        page = convertParameter(parameterObject, page);
    }

    // 
    if (page != null && page.getPageSize() != -1) {

        if (StringUtils.isBlank(boundSql.getSql())) {
            return null;
        }
        String originalSql = boundSql.getSql().trim();

        // 
        page.setCount(SQLHelper.getCount(originalSql, null, mappedStatement, parameterObject, boundSql, log));

        //   ??
        String pageSql = SQLHelper.generatePageSql(originalSql, page, DIALECT);
        // if (log.isDebugEnabled()) {
        // log.debug("PAGE SQL:" + StringUtils.replace(pageSql, "\n", ""));
        // }
        invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
        BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), pageSql,
                boundSql.getParameterMappings(), boundSql.getParameterObject());
        MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));

        invocation.getArgs()[0] = newMs;
    }
    // }
    return invocation.proceed();
}

From source file:com.sinotopia.mybatis.pagehelper.dialect.AbstractHelperDialect.java

License:Open Source License

@Override
public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds,
        CacheKey countKey) {// w w w .  j av a  2 s.c o m
    Page<Object> page = getLocalPage();
    String countColumn = page.getCountColumn();
    if (StringUtil.isNotEmpty(countColumn)) {
        return countSqlParser.getSmartCountSql(boundSql.getSql(), countColumn);
    }
    return countSqlParser.getSmartCountSql(boundSql.getSql());
}