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

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

Introduction

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

Prototype

public List<ParameterMapping> getParameterMappings() 

Source Link

Usage

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

License:Apache License

@Override
public BoundSql getBoundSql(Object parameterObject) {
    BoundSql subBoundSql = new BoundSql(configuration, sql, parameterMappings, parameterObject);
    for (ParameterMapping parameterMapping : subBoundSql.getParameterMappings()) {
        String property = new PropertyTokenizer(parameterMapping.getProperty()).getName();
        if (parentBoundSql.hasAdditionalParameter(property)) {
            subBoundSql.setAdditionalParameter(property, parentBoundSql.getAdditionalParameter(property));
        }/*w  w  w.j a v  a2s . c o  m*/
    }
    return subBoundSql;
}

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  w  w. j  a  v a  2s . c  om*/
    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

/**
 *
 * @param page/*ww  w.j  ava2s  .  c om*/
 * @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.mook.locker.interceptor.OptimisticLocker.java

License:Apache License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object intercept(Invocation invocation) throws Exception {

    String interceptMethod = invocation.getMethod().getName();
    String versionColumn = props.getProperty("versionColumn", "version");

    if ("prepare".equals(interceptMethod)) {

        StatementHandler handler = (StatementHandler) invocation.getTarget();
        MetaObject hm = SystemMetaObject.forObject(handler);

        MappedStatement ms = (MappedStatement) hm.getValue("delegate.mappedStatement");
        SqlCommandType sqlCmdType = ms.getSqlCommandType();
        if (sqlCmdType != SqlCommandType.UPDATE) {
            return invocation.proceed();
        }// w w w.  j  a  v  a 2 s .c om

        BoundSql boundSql = (BoundSql) hm.getValue("delegate.boundSql");
        if (hasVersionLocker(ms, boundSql)) {
            return invocation.proceed();
        }

        Object originalVersion = hm.getValue("delegate.boundSql.parameterObject.version");
        Object versionIncr = castTypeAndOptValue(originalVersion,
                hm.getValue("delegate.boundSql.parameterObject"), ValueType.INCREASE);
        hm.setValue("delegate.boundSql.parameterObject.version", versionIncr);

        String originalSql = (String) hm.getValue("delegate.boundSql.sql");
        StringBuilder builder = new StringBuilder(originalSql);
        builder.append(" and ");
        builder.append(versionColumn);
        builder.append(" = ?");
        hm.setValue("delegate.boundSql.sql", builder.toString());

        if (log.isDebugEnabled()) {
            log.debug("==> originalSql: " + originalSql);
        }

        return invocation.proceed();

    } else if ("setParameters".equals(interceptMethod)) {

        ParameterHandler handler = (ParameterHandler) invocation.getTarget();
        MetaObject hm = SystemMetaObject.forObject(handler);

        MappedStatement ms = (MappedStatement) hm.getValue("mappedStatement");
        SqlCommandType sqlCmdType = ms.getSqlCommandType();
        if (sqlCmdType != SqlCommandType.UPDATE) {
            return invocation.proceed();
        }

        Configuration configuration = (Configuration) hm.getValue("configuration");
        BoundSql boundSql = (BoundSql) hm.getValue("boundSql");

        if (hasVersionLocker(ms, boundSql)) {
            return invocation.proceed();
        }

        Object result = invocation.proceed();

        ParameterMapping versionMapping = new ParameterMapping.Builder(configuration, versionColumn,
                Object.class).build();

        Object parameterObject = boundSql.getParameterObject();

        MetaObject pm = configuration.newMetaObject(parameterObject);
        if (parameterObject instanceof MapperMethod.ParamMap<?>) {
            MapperMethod.ParamMap<?> paramMap = (MapperMethod.ParamMap<?>) parameterObject;
            if (!paramMap.containsKey(versionColumn)) {
                throw new TypeException("??MyBatis@Param");
            }
        }
        Object value = pm.getValue(versionColumn);
        TypeHandler typeHandler = versionMapping.getTypeHandler();
        JdbcType jdbcType = versionMapping.getJdbcType();

        if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
        }
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        try {
            PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
            Object val = castTypeAndOptValue(value, parameterObject, ValueType.DECREASE);
            typeHandler.setParameter(ps, parameterMappings.size() + 1, val, jdbcType);
        } catch (TypeException e) {
            throw new TypeException(
                    "Could not set parameters for mapping: " + parameterMappings + ". Cause: " + e, e);
        } catch (SQLException e) {
            throw new TypeException(
                    "Could not set parameters for mapping: " + parameterMappings + ". Cause: " + e, e);
        }
        return result;
    }
    return invocation.proceed();
}

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

License:Apache License

/**
 * ?//from w  ww . j av  a2  s. co m
 *
 * @param sql
 * @param connection
 * @param mappedStatement
 * @param boundSql
 * @param page
 */
public Pagination count(String sql, Connection connection, MappedStatement mappedStatement, BoundSql boundSql,
        Pagination page) {
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = connection.prepareStatement(sql);
        BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), sql,
                boundSql.getParameterMappings(), boundSql.getParameterObject());
        ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement,
                boundSql.getParameterObject(), countBS);
        parameterHandler.setParameters(pstmt);
        rs = pstmt.executeQuery();
        int total = 0;
        if (rs.next()) {
            total = rs.getInt(1);
        }
        page.setTotal(total);
        /*
         * 
         */
        if (overflowCurrent && (page.getCurrent() > page.getPages())) {
            page = new Pagination(1, page.getSize());
            page.setTotal(total);
        }
    } catch (Exception e) {
        // ignored
    } finally {
        IOUtils.closeQuietly(pstmt, rs);
    }
    return page;
}

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

License:Apache License

private List<String> getParams(BoundSql boundSql, Object parameterObject, Configuration configuration) {
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
    List<String> params = new ArrayList<String>();
    if (parameterMappings != null) {
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;//from   ww w.j av a 2s  .  com
                String propertyName = parameterMapping.getProperty();
                if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (parameterObject == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(parameterObject);
                    value = metaObject.getValue(propertyName);
                }
                params.add(StringUtils.sqlParam(value));
            }
        }
    }
    return params;
}

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

License:Apache License

/**
 * <p>/*from  www .  java 2 s. co  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.playersun.jbf.common.persistence.mybatis.pagination.CountHelper.java

License:Apache License

/**
 * SQL?(?)/*from   w  w w  .  j ava 2  s  . c o  m*/
 * 
 * @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);
                }
                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());
            }
        }
    }
}

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  w w  . j  a va 2s. com*/
    // // 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.PageInterceptor.java

License:Open Source License

@Override
public Object intercept(Invocation invocation) throws Throwable {
    try {//from   w  w  w . ja v a 2s.c om
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        //?
        if (args.length == 4) {
            //4 ?
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            //6 ?
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        List resultList;
        //????
        if (!dialect.skip(ms, parameter, rowBounds)) {
            //?????
            String msId = ms.getId();
            Configuration configuration = ms.getConfiguration();
            Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField
                    .get(boundSql);
            //?? count 
            if (dialect.beforeCount(ms, parameter, rowBounds)) {
                String countMsId = msId + countSuffix;
                Long count;
                //? count 
                MappedStatement countMs = getExistedMappedStatement(configuration, countMsId);
                if (countMs != null) {
                    count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler);
                } else {
                    countMs = msCountMap.get(countMsId);
                    //
                    if (countMs == null) {
                        //?? ms  Long  ms
                        countMs = MSUtils.newCountMappedStatement(ms, countMsId);
                        msCountMap.put(countMsId, countMs);
                    }
                    count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler);
                }
                //?
                // true false 
                if (!dialect.afterCount(count, parameter, rowBounds)) {
                    // 0 
                    return dialect.afterPage(new ArrayList(), parameter, rowBounds);
                }
            }
            //??
            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(configuration, pageSql, boundSql.getParameterMappings(),
                        parameter);
                //??
                for (String key : additionalParameters.keySet()) {
                    pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
                }
                //
                resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey,
                        pageBoundSql);
            } else {
                //??
                resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey,
                        boundSql);
            }
        } else {
            //rowBounds??????
            resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
        }
        return dialect.afterPage(resultList, parameter, rowBounds);
    } finally {
        dialect.afterAll();
    }
}