Search in sources :

Example 36 with MappedStatement

use of org.apache.ibatis.mapping.MappedStatement in project mybatis-paginator by HuQingmiao.

the class OffsetLimitInterceptor method intercept.

public Object intercept(final Invocation invocation) throws Throwable {
    final Executor executor = (Executor) invocation.getTarget();
    final Object[] queryArgs = invocation.getArgs();
    final MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
    final Object parameter = queryArgs[PARAMETER_INDEX];
    final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];
    //DAO接口中没有传PageBounds参量
    if (!(rowBounds instanceof PageBounds)) {
        return invocation.proceed();
    }
    //DAO接口传有PageBounds参量
    PageBounds pageBounds = (PageBounds) rowBounds;
    if (pageBounds.notValid()) {
        return new PageList((List) invocation.proceed());
    }
    final Dialect dialect;
    try {
        Class clazz = Class.forName(dialectClass);
        Constructor constructor = clazz.getConstructor(MappedStatement.class, Object.class, PageBounds.class);
        dialect = (Dialect) constructor.newInstance(new Object[] { ms, parameter, pageBounds });
    } catch (Exception e) {
        throw new ClassNotFoundException("Cannot create dialect instance: " + dialectClass, e);
    }
    final BoundSql boundSql = ms.getBoundSql(parameter);
    queryArgs[MAPPED_STATEMENT_INDEX] = copyFromNewSql(ms, boundSql, dialect.getPageSQL(), dialect.getParameterMappings(), dialect.getParameterObject());
    queryArgs[PARAMETER_INDEX] = dialect.getParameterObject();
    queryArgs[ROWBOUNDS_INDEX] = new RowBounds();
    //采用同步方式,执行分页查询
    //修复bug: 提交后台线程破坏了spring 事务管理,参见TransactionSynchronizationManager
    Callable<List> queryThread = new Callable<List>() {

        public List call() throws Exception {
            return (List) invocation.proceed();
        }
    };
    Future<List> queryFuture = call(queryThread, false);
    //如果不需要count总的结果集,则直接返回分页查询结果
    if (!pageBounds.isIfCount()) {
        return new PageList(queryFuture.get());
    }
    //对总的结果集进行count
    Callable<Integer> countThread = new Callable<Integer>() {

        public Integer call() throws Exception {
            Cache cache = ms.getCache();
            Integer count = null;
            if (cache != null && ms.isUseCache() && ms.getConfiguration().isCacheEnabled()) {
                CacheKey cacheKey = executor.createCacheKey(ms, parameter, new RowBounds(), copyFromBoundSql(ms, boundSql, dialect.getCountSQL(), boundSql.getParameterMappings(), boundSql.getParameterObject()));
                count = (Integer) cache.getObject(cacheKey);
                if (count == null) {
                    count = SQLHelp.getCount(ms, parameter, boundSql, dialect);
                    cache.putObject(cacheKey, count);
                }
            } else {
                count = SQLHelp.getCount(ms, parameter, boundSql, dialect);
            }
            return count;
        }
    };
    Future<Integer> countFutrue = call(countThread, false);
    return new PageList(queryFuture.get(), countFutrue.get().intValue());
}
Also used : Constructor(java.lang.reflect.Constructor) RowBounds(org.apache.ibatis.session.RowBounds) Executor(org.apache.ibatis.executor.Executor) BoundSql(org.apache.ibatis.mapping.BoundSql) Dialect(com.github.walker.mybatis.paginator.dialect.Dialect) List(java.util.List) MappedStatement(org.apache.ibatis.mapping.MappedStatement) CacheKey(org.apache.ibatis.cache.CacheKey) Cache(org.apache.ibatis.cache.Cache)

Example 37 with MappedStatement

use of org.apache.ibatis.mapping.MappedStatement in project Mybatis-PageHelper by pagehelper.

the class MSUtils method newCountMappedStatement.

/**
     * 新建count查询和分页查询的MappedStatement
     *
     * @param ms
     * @return
     */
public static MappedStatement newCountMappedStatement(MappedStatement ms) {
    MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId() + COUNT, ms.getSqlSource(), ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
        StringBuilder keyProperties = new StringBuilder();
        for (String keyProperty : ms.getKeyProperties()) {
            keyProperties.append(keyProperty).append(",");
        }
        keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
        builder.keyProperty(keyProperties.toString());
    }
    builder.timeout(ms.getTimeout());
    builder.parameterMap(ms.getParameterMap());
    //count查询返回值int
    List<ResultMap> resultMaps = new ArrayList<ResultMap>();
    ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), Long.class, EMPTY_RESULTMAPPING).build();
    resultMaps.add(resultMap);
    builder.resultMaps(resultMaps);
    builder.resultSetType(ms.getResultSetType());
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());
    return builder.build();
}
Also used : ResultMap(org.apache.ibatis.mapping.ResultMap) ArrayList(java.util.ArrayList) MappedStatement(org.apache.ibatis.mapping.MappedStatement)

Example 38 with MappedStatement

use of org.apache.ibatis.mapping.MappedStatement in project mybatis-3 by mybatis.

the class XMLStatementBuilder method parseSelectKeyNode.

private void parseSelectKeyNode(String id, XNode nodeToHandle, Class<?> parameterTypeClass, LanguageDriver langDriver, String databaseId) {
    String resultType = nodeToHandle.getStringAttribute("resultType");
    Class<?> resultTypeClass = resolveClass(resultType);
    StatementType statementType = StatementType.valueOf(nodeToHandle.getStringAttribute("statementType", StatementType.PREPARED.toString()));
    String keyProperty = nodeToHandle.getStringAttribute("keyProperty");
    String keyColumn = nodeToHandle.getStringAttribute("keyColumn");
    boolean executeBefore = "BEFORE".equals(nodeToHandle.getStringAttribute("order", "AFTER"));
    //defaults
    boolean useCache = false;
    boolean resultOrdered = false;
    KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;
    Integer fetchSize = null;
    Integer timeout = null;
    boolean flushCache = false;
    String parameterMap = null;
    String resultMap = null;
    ResultSetType resultSetTypeEnum = null;
    SqlSource sqlSource = langDriver.createSqlSource(configuration, nodeToHandle, parameterTypeClass);
    SqlCommandType sqlCommandType = SqlCommandType.SELECT;
    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache, resultOrdered, keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null);
    id = builderAssistant.applyCurrentNamespace(id, false);
    MappedStatement keyStatement = configuration.getMappedStatement(id, false);
    configuration.addKeyGenerator(id, new SelectKeyGenerator(keyStatement, executeBefore));
}
Also used : SqlSource(org.apache.ibatis.mapping.SqlSource) ResultSetType(org.apache.ibatis.mapping.ResultSetType) StatementType(org.apache.ibatis.mapping.StatementType) SqlCommandType(org.apache.ibatis.mapping.SqlCommandType) SelectKeyGenerator(org.apache.ibatis.executor.keygen.SelectKeyGenerator) MappedStatement(org.apache.ibatis.mapping.MappedStatement) NoKeyGenerator(org.apache.ibatis.executor.keygen.NoKeyGenerator) Jdbc3KeyGenerator(org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator) KeyGenerator(org.apache.ibatis.executor.keygen.KeyGenerator) SelectKeyGenerator(org.apache.ibatis.executor.keygen.SelectKeyGenerator)

Example 39 with MappedStatement

use of org.apache.ibatis.mapping.MappedStatement in project mybatis-3 by mybatis.

the class BatchExecutor method doUpdate.

@Override
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();
    final String sql = boundSql.getSql();
    final Statement stmt;
    if (sql.equals(currentSql) && ms.equals(currentStatement)) {
        int last = statementList.size() - 1;
        stmt = statementList.get(last);
        applyTransactionTimeout(stmt);
        //fix Issues 322
        handler.parameterize(stmt);
        BatchResult batchResult = batchResultList.get(last);
        batchResult.addParameterObject(parameterObject);
    } else {
        Connection connection = getConnection(ms.getStatementLog());
        stmt = handler.prepare(connection, transaction.getTimeout());
        //fix Issues 322
        handler.parameterize(stmt);
        currentSql = sql;
        currentStatement = ms;
        statementList.add(stmt);
        batchResultList.add(new BatchResult(ms, sql, parameterObject));
    }
    // handler.parameterize(stmt);
    handler.batch(stmt);
    return BATCH_UPDATE_RETURN_VALUE;
}
Also used : Configuration(org.apache.ibatis.session.Configuration) BoundSql(org.apache.ibatis.mapping.BoundSql) MappedStatement(org.apache.ibatis.mapping.MappedStatement) Statement(java.sql.Statement) StatementHandler(org.apache.ibatis.executor.statement.StatementHandler) Connection(java.sql.Connection)

Example 40 with MappedStatement

use of org.apache.ibatis.mapping.MappedStatement in project mybatis-3 by mybatis.

the class BatchExecutor method doQuery.

@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, transaction.getTimeout());
        handler.parameterize(stmt);
        return handler.<E>query(stmt, resultHandler);
    } finally {
        closeStatement(stmt);
    }
}
Also used : Configuration(org.apache.ibatis.session.Configuration) MappedStatement(org.apache.ibatis.mapping.MappedStatement) Statement(java.sql.Statement) StatementHandler(org.apache.ibatis.executor.statement.StatementHandler) Connection(java.sql.Connection)

Aggregations

MappedStatement (org.apache.ibatis.mapping.MappedStatement)73 Test (org.junit.Test)27 Author (org.apache.ibatis.domain.blog.Author)19 BaseDataTest (org.apache.ibatis.BaseDataTest)18 JdbcTransaction (org.apache.ibatis.transaction.jdbc.JdbcTransaction)18 StaticSqlSource (org.apache.ibatis.builder.StaticSqlSource)17 Configuration (org.apache.ibatis.session.Configuration)17 TypeHandlerRegistry (org.apache.ibatis.type.TypeHandlerRegistry)17 ArrayList (java.util.ArrayList)15 ResultMap (org.apache.ibatis.mapping.ResultMap)12 BoundSql (org.apache.ibatis.mapping.BoundSql)11 Statement (java.sql.Statement)10 StatementHandler (org.apache.ibatis.executor.statement.StatementHandler)10 ParameterMap (org.apache.ibatis.mapping.ParameterMap)9 ParameterMapping (org.apache.ibatis.mapping.ParameterMapping)9 Section (org.apache.ibatis.domain.blog.Section)8 SqlSource (org.apache.ibatis.mapping.SqlSource)8 RowBounds (org.apache.ibatis.session.RowBounds)8 ResultMapping (org.apache.ibatis.mapping.ResultMapping)7 MetaObject (org.apache.ibatis.reflection.MetaObject)7