Search in sources :

Example 16 with ResultHandler

use of org.apache.ibatis.session.ResultHandler in project mybatis-3 by mybatis.

the class CommonPropertyDeferLoadError method testDeferLoadDuringResultHandlerWithLazyLoad.

@Test
public void testDeferLoadDuringResultHandlerWithLazyLoad() {
    SqlSession sqlSession = lazyLoadSqlSessionFactory.openSession();
    try {
        class MyResultHandler implements ResultHandler {

            @Override
            public void handleResult(ResultContext context) {
                Child child = (Child) context.getResultObject();
                assertNotNull(child.getFather());
            }
        }
        ;
        sqlSession.select("org.apache.ibatis.submitted.deferload_common_property.ChildMapper.selectAll", new MyResultHandler());
    } finally {
        sqlSession.close();
    }
}
Also used : ResultContext(org.apache.ibatis.session.ResultContext) SqlSession(org.apache.ibatis.session.SqlSession) ResultHandler(org.apache.ibatis.session.ResultHandler) Test(org.junit.Test)

Example 17 with ResultHandler

use of org.apache.ibatis.session.ResultHandler in project mybatis-3 by mybatis.

the class CommonPropertyDeferLoadError method testDeferLoadDuringResultHandler.

@Test
public void testDeferLoadDuringResultHandler() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        class MyResultHandler implements ResultHandler {

            @Override
            public void handleResult(ResultContext context) {
                Child child = (Child) context.getResultObject();
                assertNotNull(child.getFather());
            }
        }
        ;
        sqlSession.select("org.apache.ibatis.submitted.deferload_common_property.ChildMapper.selectAll", new MyResultHandler());
    } finally {
        sqlSession.close();
    }
}
Also used : ResultContext(org.apache.ibatis.session.ResultContext) SqlSession(org.apache.ibatis.session.SqlSession) ResultHandler(org.apache.ibatis.session.ResultHandler) Test(org.junit.Test)

Example 18 with ResultHandler

use of org.apache.ibatis.session.ResultHandler in project mybatis.flying by limeng32.

the class EnhancedCachingInterceptor method processQuery.

/**
 * when executing a query operation 1. record this statement's id and it's
 * corresponding Cache Object into Global Caching Manager; 2. record this
 * statement's id and
 *
 * @param invocation
 * @return
 * @throws Throwable
 */
protected Object processQuery(Invocation invocation) throws Throwable {
    Object result = invocation.proceed();
    if (cachingManager.isCacheEnabled()) {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        // 如果本条statementId表示的查询语句配置了 flushCache=true,则清空querCacheOnCommit缓存
        if (mappedStatement.isFlushCacheRequired()) {
            queryCacheOnCommit.clear();
        }
        // 和对应的二级缓存对象映射关系添加到全局缓存映射管理器中
        if (mappedStatement.isUseCache() && mappedStatement.getCache() != null) {
            cachingManager.appendStatementCacheMap(mappedStatement.getId(), mappedStatement.getCache());
        }
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        Executor executor = (Executor) invocation.getTarget();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        FlyingModel flyingModel = CookOriginalSql.fetchFlyingFeature(boundSql.getSql());
        // 记录本次查询所产生的CacheKey
        CacheKey cacheKey = createCacheKey(mappedStatement, parameter, rowBounds, boundSql, executor);
        if (flyingModel.isHasFlyingFeature()) {
            switch(flyingModel.getActionType()) {
                case count:
                    cacheKey.update(DigestUtils.md5Hex(JSON.toJSONString(parameter)));
                    break;
                case selectAll:
                    cacheKey.update(DigestUtils.md5Hex(JSON.toJSONString(parameter)));
                    break;
                case selectOne:
                    cacheKey.update(DigestUtils.md5Hex(JSON.toJSONString(parameter)));
                    break;
                default:
                    break;
            }
        }
        queryCacheOnCommit.putElement(mappedStatement.getId(), cacheKey);
        /* 处理分页 */
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executorProxy = (Executor) invocation.getTarget();
        MetaObject metaParameter = MetaObject.forObject(parameter, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
        MetaObject metaExecutor = MetaObject.forObject(executorProxy, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
        /* 当需要分页查询时,缓存里加入page信息 */
        // if (metaParameter.getOriginalObject() instanceof Conditionable) {
        Cache cache = mappedStatement.getCache();
        Object value = cache.getObject(cacheKey);
        if (metaExecutor.hasGetter("delegate")) {
            TransactionalCacheManager tcm = (TransactionalCacheManager) metaExecutor.getValue("tcm");
            Executor delegate = (Executor) metaExecutor.getValue("delegate");
            Object list = delegate.query(mappedStatement, parameter, rowBounds, resultHandler, cacheKey, boundSql);
            if (value != null) {
                return value;
            } else {
                tcm.putObject(cache, cacheKey, list);
                return list;
            }
        }
    // }
    }
    return result;
}
Also used : FlyingModel(indi.mybatis.flying.models.FlyingModel) Executor(org.apache.ibatis.executor.Executor) BoundSql(org.apache.ibatis.mapping.BoundSql) MetaObject(org.apache.ibatis.reflection.MetaObject) RowBounds(org.apache.ibatis.session.RowBounds) MetaObject(org.apache.ibatis.reflection.MetaObject) MappedStatement(org.apache.ibatis.mapping.MappedStatement) ResultHandler(org.apache.ibatis.session.ResultHandler) TransactionalCacheManager(org.apache.ibatis.cache.TransactionalCacheManager) CacheKey(org.apache.ibatis.cache.CacheKey) Cache(org.apache.ibatis.cache.Cache)

Example 19 with ResultHandler

use of org.apache.ibatis.session.ResultHandler in project jeesuite-libs by vakinge.

the class PaginationHandler method onInterceptor.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
    try {
        final Executor executor = (Executor) invocation.getTarget();
        final Object[] args = invocation.getArgs();
        final MappedStatement orignMappedStatement = (MappedStatement) args[0];
        if (!orignMappedStatement.getSqlCommandType().equals(SqlCommandType.SELECT))
            return null;
        PageParams pageParams = PageExecutor.getPageParams();
        if (pageParams == null && !pageMappedStatements.keySet().contains(orignMappedStatement.getId()))
            return null;
        final RowBounds rowBounds = (RowBounds) args[2];
        final ResultHandler resultHandler = (ResultHandler) args[3];
        final Object parameter = args[1];
        BoundSql boundSql;
        if (args.length == 4) {
            boundSql = orignMappedStatement.getBoundSql(parameter);
        } else {
            boundSql = (BoundSql) args[5];
        }
        if (pageParams == null && pageMappedStatements.get(orignMappedStatement.getId())) {
            if (parameter instanceof Map) {
                Collection parameterValues = ((Map) parameter).values();
                for (Object val : parameterValues) {
                    if (val instanceof PageParams) {
                        pageParams = (PageParams) val;
                        break;
                    }
                }
            } else {
                pageParams = (PageParams) parameter;
            }
        }
        if (pageParams == null)
            return null;
        // 查询总数
        MappedStatement countMappedStatement = getCountMappedStatement(orignMappedStatement);
        Long total = executeQueryCount(executor, countMappedStatement, parameter, boundSql, rowBounds, resultHandler);
        // 按分页查询
        MappedStatement limitMappedStatement = getLimitMappedStatementIfNotCreate(orignMappedStatement);
        List<?> datas;
        BoundSql pageBoundSql;
        if (limitMappedStatement == null) {
            if (StringUtils.isBlank(boundSql.getSql())) {
                logger.error("create_limit_mappedStatement_error。MappedStatementId:{},pageParamsHolder:{}", orignMappedStatement.getId(), PageExecutor.getPageParams());
                throw new RuntimeException("生成Limit查询语句错误");
            }
            String pageSql = PageSqlUtils.getLimitSQL(dbType, boundSql.getSql(), pageParams);
            pageBoundSql = new BoundSql(orignMappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);
            datas = executor.query(orignMappedStatement, parameter, RowBounds.DEFAULT, resultHandler, null, pageBoundSql);
        } else {
            pageBoundSql = limitMappedStatement.getBoundSql(parameter);
            pageBoundSql.setAdditionalParameter(PARAMETER_OFFSET, pageParams.offset());
            pageBoundSql.setAdditionalParameter(PARAMETER_SIZE, pageParams.getPageSize());
            // 
            datas = executor.query(limitMappedStatement, parameter, RowBounds.DEFAULT, resultHandler, null, pageBoundSql);
        }
        Page<Object> page = new Page<Object>(pageParams, total, (List<Object>) datas);
        List<Page<?>> list = new ArrayList<Page<?>>(1);
        list.add(page);
        return list;
    } finally {
        PageExecutor.clearPageParams();
    }
}
Also used : ArrayList(java.util.ArrayList) RowBounds(org.apache.ibatis.session.RowBounds) ResultHandler(org.apache.ibatis.session.ResultHandler) Executor(org.apache.ibatis.executor.Executor) BoundSql(org.apache.ibatis.mapping.BoundSql) Collection(java.util.Collection) MappedStatement(org.apache.ibatis.mapping.MappedStatement) HashMap(java.util.HashMap) Map(java.util.Map) ResultMap(org.apache.ibatis.mapping.ResultMap)

Example 20 with ResultHandler

use of org.apache.ibatis.session.ResultHandler in project luntan by caoawei.

the class MybatisPageInterceptor method intercept.

@Override
public Object intercept(Invocation invocation) throws Throwable {
    if (PageUtil.needPage() && sqlParser.isSupport(DBType.MYSQL)) {
        Executor executor = (Executor) invocation.getTarget();
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        Object parameterObject = invocation.getArgs()[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];
        ResultHandler resultHandler = (ResultHandler) invocation.getArgs()[3];
        Connection connection = executor.getTransaction().getConnection();
        String countSql = sqlParser.parseWithCountQuery(boundSql.getSql().trim());
        BoundSql countBoundSql = copyBoundSql(ms, boundSql, countSql);
        PreparedStatement ps = connection.prepareStatement(countSql);
        setParameters(ps, ms, countBoundSql);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            PageParam pageParam = resolvePageParam(resultSet);
            PageList pageList = initPageList(pageParam);
            String pageSql = sqlParser.parseWithPageQuery(boundSql.getSql().trim());
            Utils.setFieldValue("sql", boundSql, pageSql);
            List list = query(executor, ms, parameterObject, boundSql, rowBounds, resultHandler);
            pageList.addAll(list);
            return pageList;
        }
        resultSet.close();
        connection.close();
    }
    return invocation.proceed();
}
Also used : Connection(java.sql.Connection) RowBounds(org.apache.ibatis.session.RowBounds) PreparedStatement(java.sql.PreparedStatement) ResultHandler(org.apache.ibatis.session.ResultHandler) Executor(org.apache.ibatis.executor.Executor) BaseExecutor(org.apache.ibatis.executor.BaseExecutor) BoundSql(org.apache.ibatis.mapping.BoundSql) ResultSet(java.sql.ResultSet) MetaObject(org.apache.ibatis.reflection.MetaObject) PageList(com.optimus.common.mybatis.PageList) List(java.util.List) MappedStatement(org.apache.ibatis.mapping.MappedStatement) PageParam(com.optimus.common.mybatis.PageParam) PageList(com.optimus.common.mybatis.PageList)

Aggregations

ResultHandler (org.apache.ibatis.session.ResultHandler)25 ResultContext (org.apache.ibatis.session.ResultContext)17 ArrayList (java.util.ArrayList)16 List (java.util.List)14 Test (org.junit.Test)13 SqlSession (org.apache.ibatis.session.SqlSession)10 RowBounds (org.apache.ibatis.session.RowBounds)8 Random (java.util.Random)7 Consumer (java.util.function.Consumer)7 RandomStringUtils.randomAlphabetic (org.apache.commons.lang.RandomStringUtils.randomAlphabetic)7 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)7 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)6 DataProviderRunner (com.tngtech.java.junit.dataprovider.DataProviderRunner)6 UseDataProvider (com.tngtech.java.junit.dataprovider.UseDataProvider)6 Arrays (java.util.Arrays)6 Date (java.util.Date)6 IntStream (java.util.stream.IntStream)6 Executor (org.apache.ibatis.executor.Executor)6 BoundSql (org.apache.ibatis.mapping.BoundSql)6 MappedStatement (org.apache.ibatis.mapping.MappedStatement)6