Example usage for org.apache.ibatis.executor Executor getTransaction

List of usage examples for org.apache.ibatis.executor Executor getTransaction

Introduction

In this page you can find the example usage for org.apache.ibatis.executor Executor getTransaction.

Prototype

Transaction getTransaction();

Source Link

Usage

From source file:com.baomidou.mybatisplus.plugins.CachePaginationInterceptor.java

License:Apache License

/**
 * Physical Pagination Interceptor for all the queries with parameter
 * {@link org.apache.ibatis.session.RowBounds}
 *//*from   w ww  . j a  va 2s. c o m*/
public Object intercept(Invocation invocation) throws Throwable {

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

        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        String originalSql = boundSql.getSql();

        if (rowBounds instanceof Pagination) {
            Pagination page = (Pagination) rowBounds;
            boolean orderBy = true;
            if (page.isSearchCount()) {
                CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType, dialectType,
                        page.isOptimizeCount());
                orderBy = countOptimize.isOrderBy();
            }
            String buildSql = SqlUtils.concatOrderBy(originalSql, page, orderBy);
            originalSql = DialectFactory.buildPaginationSql(page, buildSql, dialectType, dialectClazz);
        } else {
            // support physical Pagination for RowBounds
            originalSql = DialectFactory.buildPaginationSql(rowBounds, originalSql, dialectType, dialectClazz);
        }

        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
        metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
        metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
    } else {
        RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];
        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Executor executor = (Executor) invocation.getTarget();
        Connection connection = executor.getTransaction().getConnection();
        Object parameterObject = invocation.getArgs()[1];
        BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
        String originalSql = boundSql.getSql();
        if (rowBounds instanceof Pagination) {
            Pagination page = (Pagination) rowBounds;
            if (page.isSearchCount()) {
                CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType, dialectType,
                        page.isOptimizeCount());
                super.queryTotal(countOptimize.getCountSQL(), mappedStatement, boundSql, page, connection);
                if (page.getTotal() <= 0) {
                    return invocation.proceed();
                }
            }
        }
    }
    return invocation.proceed();
}

From source file:com.baomidou.mybatisplus.plugins.SqlExplainInterceptor.java

License:Apache License

public Object intercept(Invocation invocation) throws Throwable {
    /**/*ww w  .j a v  a 2  s  .c om*/
     * ? DELETE UPDATE ?
     */
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    if (ms.getSqlCommandType() == SqlCommandType.DELETE || ms.getSqlCommandType() == SqlCommandType.UPDATE) {
        Executor executor = (Executor) invocation.getTarget();
        Configuration configuration = ms.getConfiguration();
        Object parameter = invocation.getArgs()[1];
        BoundSql boundSql = ms.getBoundSql(parameter);
        Connection connection = executor.getTransaction().getConnection();
        String databaseVersion = connection.getMetaData().getDatabaseProductVersion();
        if (GlobalConfiguration.getDbType(configuration).equals(DBType.MYSQL)
                && VersionUtils.compare(minMySQLVersion, databaseVersion)) {
            logger.warn("Warn: Your mysql version needs to be greater than '5.6.3' to execute of Sql Explain!");
            return invocation.proceed();
        }
        /**
         *  SQL ?
         */
        sqlExplain(configuration, ms, boundSql, connection, parameter);
    }
    return invocation.proceed();
}

From source file:com.github.ibole.infrastructure.persistence.db.mybatis.pagination.PaginationInterceptor.java

License:Apache License

private Integer getCount(String sql, Executor executor, MappedStatement ms, RowBounds rowBounds,
        BoundSql boundSql, Object parameter, Dialect dialect) throws SQLException {
    Integer count = 0;//from  ww w  .ja  v a  2s. c  o  m
    Cache cache = ms.getCache();
    if (cache != null && ms.isUseCache() && ms.getConfiguration().isCacheEnabled()) {
        CacheKey cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        count = (Integer) cache.getObject(cacheKey);
        if (count == null) {
            count = SqlHelper.getCount(sql, ms, executor.getTransaction(), parameter, boundSql, dialect);
            cache.putObject(cacheKey, count);
        }
    } else {
        count = SqlHelper.getCount(sql, ms, executor.getTransaction(), parameter, boundSql, dialect);
    }
    return count;
}

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

License:Apache License

public Object intercept(Invocation invocation) throws Throwable {
    /**/*from  ww  w  .  jav a  2 s. c  om*/
     * ? DELETE UPDATE ?
     */
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    if (ms.getSqlCommandType() == SqlCommandType.DELETE || ms.getSqlCommandType() == SqlCommandType.UPDATE) {
        Configuration configuration = ms.getConfiguration();
        Object parameter = invocation.getArgs()[1];
        BoundSql boundSql = ms.getBoundSql(parameter);
        Executor exe = (Executor) invocation.getTarget();
        Connection connection = exe.getTransaction().getConnection();

        /**
         *  SQL ?
         */
        sqlExplain(configuration, ms, boundSql, connection, parameter);
    }
    return invocation.proceed();
}

From source file:com.sinotopia.mybatis.mapper.mapperhelper.SelectKeyGenerator.java

License:Apache License

private void processGeneratedKeys(Executor executor, MappedStatement ms, Object parameter) {
    try {/*from   ww w.  j a  v a  2 s .  co m*/
        if (parameter != null && keyStatement != null && keyStatement.getKeyProperties() != null) {
            String[] keyProperties = keyStatement.getKeyProperties();
            final Configuration configuration = ms.getConfiguration();
            final MetaObject metaParam = configuration.newMetaObject(parameter);
            if (keyProperties != null) {
                // Do not close keyExecutor.
                // The transaction will be closed by parent executor.
                Executor keyExecutor = configuration.newExecutor(executor.getTransaction(),
                        ExecutorType.SIMPLE);
                List<Object> values = keyExecutor.query(keyStatement, parameter, RowBounds.DEFAULT,
                        Executor.NO_RESULT_HANDLER);
                if (values.size() == 0) {
                    throw new ExecutorException("SelectKey returned no data.");
                } else if (values.size() > 1) {
                    throw new ExecutorException("SelectKey returned more than one value.");
                } else {
                    MetaObject metaResult = configuration.newMetaObject(values.get(0));
                    if (keyProperties.length == 1) {
                        if (metaResult.hasGetter(keyProperties[0])) {
                            setValue(metaParam, keyProperties[0], metaResult.getValue(keyProperties[0]));
                        } else {
                            // no getter for the property - maybe just a single value object
                            // so try that
                            setValue(metaParam, keyProperties[0], values.get(0));
                        }
                    } else {
                        handleMultipleProperties(keyProperties, metaParam, metaResult);
                    }
                }
            }
        }
    } catch (ExecutorException e) {
        throw e;
    } catch (Exception e) {
        throw new ExecutorException("Error selecting key or setting result to parameter object. Cause: " + e,
                e);
    }
}

From source file:se.spagettikod.optimist.impl.OptimisticLockingInterceptor.java

License:Open Source License

@Override
public Object intercept(Invocation invocation) throws Throwable {
    EntityWrapper entityWrapper = null;//from  w w w  .java 2 s. com
    MappedStatement ms = null;

    Executor executor = (Executor) invocation.getTarget();
    Connection connection = executor.getTransaction().getConnection();

    if (mapper == null) {
        log.info("Mapper not initialized, trying to find appropriate mapper using database metadata.");
        mapper = MapResolver.getMapper(connection);
    }

    if (invocation.getArgs() != null && invocation.getArgs().length > 0 && invocation.getArgs()[0] != null
            && invocation.getArgs()[0] instanceof MappedStatement) {

        ms = (MappedStatement) invocation.getArgs()[0];
        Object obj = invocation.getArgs()[1];

        if (EntityWrapper.hasOptimisticLockingAnnotation(obj)) {
            //
            // Increment the version number when intercepting an UPDATE
            // statement.
            //
            if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
                entityWrapper = new EntityWrapper(obj);
                updateImpl(connection, entityWrapper);
            }
            //
            // Version number set to 0 during insert.
            //
            else if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
                entityWrapper = new EntityWrapper(obj);
                entityWrapper.initVersion();
            }
            //
            // Make sure the object is not stale or has been removed when
            // deleting.
            //
            else if (ms.getSqlCommandType() == SqlCommandType.DELETE) {
                entityWrapper = new EntityWrapper(obj);
                deleteImpl(connection, entityWrapper);
            }
        } else if (ms.getSqlCommandType() == SqlCommandType.DELETE
                || ms.getSqlCommandType() == SqlCommandType.INSERT
                || ms.getSqlCommandType() == SqlCommandType.UPDATE) {
            if (obj == null) {
                log.debug("Optimistic locking can not be applied! Parameter is null.");
            } else {
                log.debug("Optimistic locking can not be applied! Parameter type '" + obj.getClass().getName()
                        + "' does not have the annotation @OptimisticLocking.");
            }
        }
    }
    return invocation.proceed();
}