Java Code Examples for org.apache.ibatis.session.ResultHandler

The following examples show how to use org.apache.ibatis.session.ResultHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: pinpoint   Source File: SqlSessionTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected final void testAndVerifySelect() throws Exception {
    // Given
    final String selectId = "selectId";
    SqlSession sqlSession = getSqlSession();
    // When
    sqlSession.select(selectId, new DefaultResultHandler());
    sqlSession.select(selectId, new Object(), new DefaultResultHandler());
    sqlSession.select(selectId, new Object(), RowBounds.DEFAULT, new DefaultResultHandler());
    // Then
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    Method select1 = sqlSession.getClass().getDeclaredMethod("select", String.class, ResultHandler.class);
    verifier.verifyTrace(event("MYBATIS", select1, Expectations.cachedArgs(selectId)));
    Method select2 = sqlSession.getClass().getDeclaredMethod("select", String.class, Object.class,
            ResultHandler.class);
    verifier.verifyTrace(event("MYBATIS", select2, Expectations.cachedArgs(selectId)));
    Method select3 = sqlSession.getClass().getDeclaredMethod("select", String.class, Object.class, RowBounds.class,
            ResultHandler.class);
    verifier.verifyTrace(event("MYBATIS", select3, Expectations.cachedArgs(selectId)));
}
 
Example 2
Source Project: QuickProject   Source File: SortListInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
       List<Sort> sortList = getSortList();
       if (sortList == null || sortList.size() == 0) {
           return invocation.proceed();
       }

       Executor executor = (Executor) invocation.getTarget();
       Object[] args = invocation.getArgs();
       MappedStatement ms = (MappedStatement) args[0];
       Object parameter = args[1];
       RowBounds rowBounds = (RowBounds) args[2];
       ResultHandler resultHandler = (ResultHandler) args[3];

       // 计算修改BoundSql
       BoundSql boundSql = ms.getBoundSql(parameter);
       MetaObject boundSqlHandler = MetaObject.forObject(boundSql, new DefaultObjectFactory(), new DefaultObjectWrapperFactory());
       Dialect dialect = DialectParser.parse(ms.getConfiguration());
       String sql = (String) boundSqlHandler.getValue("sql");
       sql = dialect.addSortString(sql, sortList);
       boundSqlHandler.setValue("sql", sql);

       // 继续执行原来的代码
       CacheKey key = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
       return executor.query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
 
Example 3
@Override
@SuppressWarnings("rawtypes")
public List<NodePropertyEntity> selectNodePropertiesByTypes(Set<QName> qnames)
{
    final List<NodePropertyEntity> properties = new ArrayList<NodePropertyEntity>();

    // qnames of properties that are encrypted
    Set<Long> qnameIds = qnameDAO.convertQNamesToIds(qnames, false);
    if(qnameIds.size() > 0)
    {
        IdsEntity param = new IdsEntity();
        param.setIds(new ArrayList<Long>(qnameIds));
        // TODO - use a callback approach
        template.select(SELECT_PROPERTIES_BY_TYPES, param, new ResultHandler()
        {
            @Override
            public void handleResult(ResultContext context)
            {
                properties.add((NodePropertyEntity)context.getResultObject());
            }
        });
    }

    return properties;
}
 
Example 4
@SuppressWarnings("rawtypes")
@Override
public List<NodePropertyEntity> selectNodePropertiesByDataType(QName dataType, long minNodeId, long maxNodeId)
{
    int typeOrdinal = NodePropertyValue.convertToTypeOrdinal(dataType);
    
    IdsEntity ids = new IdsEntity();
    ids.setIdOne((long)typeOrdinal);
    ids.setIdTwo(minNodeId);
    ids.setIdThree(maxNodeId);
    final List<NodePropertyEntity> properties = new ArrayList<NodePropertyEntity>();
    
    template.select(SELECT_PROPERTIES_BY_ACTUAL_TYPE, ids, new ResultHandler()
    {
        @Override
        public void handleResult(ResultContext context)
        {
            properties.add((NodePropertyEntity)context.getResultObject());
        }
    });
    
    return properties;
}
 
Example 5
@Override
protected void selectNodesWithAspects(
        List<Long> qnameIds,
        Long minNodeId, Long maxNodeId,
        final NodeRefQueryCallback resultsCallback)
{
    @SuppressWarnings("rawtypes")
    ResultHandler resultHandler = new ResultHandler()
    {
        public void handleResult(ResultContext context)
        {
            NodeEntity entity = (NodeEntity) context.getResultObject();
            Pair<Long, NodeRef> nodePair = new Pair<Long, NodeRef>(entity.getId(), entity.getNodeRef());
            resultsCallback.handle(nodePair);
        }
    };
    
    IdsEntity parameters = new IdsEntity();
    parameters.setIdOne(minNodeId);
    parameters.setIdTwo(maxNodeId);
    parameters.setIds(qnameIds);
    template.select(SELECT_NODES_WITH_ASPECT_IDS, parameters, resultHandler);
}
 
Example 6
/**
 * @param keyProperties         the properties that make up the unique key
 * @param collectionProperty    the property mapped using a nested <b>ResultMap</b>
 * @param resultHandler         the result handler that will receive the rolled-up results
 * @param maxResults            the maximum number of results to retrieve (-1 for no limit).
 *                              Make sure that the query result limit is large enough to produce this
 *                              at least this number of results
 */
public RollupResultHandler(Configuration configuration, String[] keyProperties, String collectionProperty, ResultHandler resultHandler, int maxResults)
{
    if (keyProperties == null || keyProperties.length == 0)
    {
        throw new IllegalArgumentException("RollupRowHandler can only be used with at least one key property.");
    }
    if (collectionProperty == null)
    {
        throw new IllegalArgumentException("RollupRowHandler must have a collection property.");
    }
    this.configuration = configuration;
    this.keyProperties = keyProperties;
    this.collectionProperty = collectionProperty;
    this.resultHandler = resultHandler;
    this.maxResults = maxResults;
    this.rawResults = new ArrayList<Object>(100);
}
 
Example 7
@Override
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler)
{
    long startTime = System.currentTimeMillis();
    PassThroughMetricsResultsHandler passThroughHandler = new PassThroughMetricsResultsHandler(handler, startTime, statement);
    try
    {
        this.sqlSession.select(statement, parameter, rowBounds, passThroughHandler);
    }
    finally
    {
        if (!passThroughHandler.hasQueryExecutionTimeBeenReported())
        {
            reportQueryExecuted(startTime, SELECT_LABEL, statement);
        }
    }
}
 
Example 8
Source Project: mybatis   Source File: BaseStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
  this.configuration = mappedStatement.getConfiguration();
  this.executor = executor;
  this.mappedStatement = mappedStatement;
  this.rowBounds = rowBounds;

  this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  this.objectFactory = configuration.getObjectFactory();

  if (boundSql == null) { // issue #435, get the key before calculating the statement
    generateKeys(parameterObject);
    boundSql = mappedStatement.getBoundSql(parameterObject);
  }

  this.boundSql = boundSql;

  //生成parameterHandler
  this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
  //生成resultSetHandler
  this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
}
 
Example 9
Source Project: mybatis   Source File: NestedResultHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
// issue #542
public void testGetPersonWithHandler() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    sqlSession.select("getPersons", new ResultHandler() {
      public void handleResult(ResultContext context) {
        Person person = (Person) context.getResultObject();
        if ("grandma".equals(person.getName())) {
          Assert.assertEquals(2, person.getItems().size());
        }
      }
    });
  } finally {
    sqlSession.close();
  }
}
 
Example 10
Source Project: azeroth   Source File: PaginationHandler.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private Long executeQueryCount(Executor executor, MappedStatement countMs, Object parameter,
                               BoundSql boundSql, RowBounds rowBounds,
                               ResultHandler resultHandler) throws IllegalAccessException,
        SQLException {
    CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT,
            boundSql);

    String orignSql = boundSql.getSql().replaceAll(";$", "");
    // count sql
    String countSql = PageSqlUtils.getCountSql(orignSql);

    BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql,
            boundSql.getParameterMappings(), parameter);
    // 执行 count 查询
    Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT,
            resultHandler, countKey, countBoundSql);
    Long count = (Long) ((List) countResultList).get(0);
    return count;
}
 
Example 11
Source Project: jeesuite-libs   Source File: PaginationHandler.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
	private Long executeQueryCount(Executor executor, MappedStatement countMs,
            Object parameter, BoundSql boundSql,
			RowBounds rowBounds, ResultHandler resultHandler) throws IllegalAccessException, SQLException {
		CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
		
		String orignSql = StringUtils.replace(boundSql.getSql(), ";$", StringUtils.EMPTY);
		// count sql
		String countSql = PageSqlUtils.getCountSql(orignSql);
		
		BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(),
				parameter);
//		for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
//			String propertyName = parameterMapping.getProperty();
//			if(boundSql.hasAdditionalParameter(propertyName)){
//				countBoundSql.setAdditionalParameter(propertyName, boundSql.getAdditionalParameter(propertyName));
//			}
//		}
		// 执行 count 查询
		Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey,
				countBoundSql);
		Long count = (Long) ((List) countResultList).get(0);
		return count;
	}
 
Example 12
Source Project: jeesuite-libs   Source File: PaginationHandler.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private List executeQuery(Executor executor, MappedStatement ms,
           Object parameter, BoundSql boundSql,
		RowBounds rowBounds, ResultHandler resultHandler,PageParams pageParams) throws IllegalAccessException, SQLException {
	CacheKey countKey = executor.createCacheKey(ms, parameter, RowBounds.DEFAULT, boundSql);
	
	String orignSql = StringUtils.replace(boundSql.getSql(), ";$", StringUtils.EMPTY);
	
	String pageSql = PageSqlUtils.getLimitSQL(dbType,orignSql,pageParams);
	
	BoundSql countBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(),
			parameter);
	
	List<?> resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, countKey,
			countBoundSql);
	return resultList;
}
 
Example 13
Source Project: mybaties   Source File: MapperMethod.java    License: Apache License 2.0 6 votes vote down vote up
private SortedMap<Integer, String> getParams(Method method, boolean hasNamedParameters) {
  //用一个TreeMap,这样就保证还是按参数的先后顺序
  final SortedMap<Integer, String> params = new TreeMap<Integer, String>();
  final Class<?>[] argTypes = method.getParameterTypes();
  for (int i = 0; i < argTypes.length; i++) {
    //是否不是RowBounds/ResultHandler类型的参数
    if (!RowBounds.class.isAssignableFrom(argTypes[i]) && !ResultHandler.class.isAssignableFrom(argTypes[i])) {
      //参数名字默认为0,1,2,这就是为什么xml里面可以用#{1}这样的写法来表示参数了
      String paramName = String.valueOf(params.size());
      if (hasNamedParameters) {
        //还可以用注解@Param来重命名参数
        paramName = getParamNameFromAnnotation(method, i, paramName);
      }
      params.put(i, paramName);
    }
  }
  return params;
}
 
Example 14
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
  final DefaultResultContext resultContext = new DefaultResultContext();
  skipRows(rsw.getResultSet(), rowBounds);
  Object rowValue = null;
  while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
    final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
    final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
    Object partialObject = nestedResultObjects.get(rowKey);
    // issue #577 && #542
    if (mappedStatement.isResultOrdered()) {
      if (partialObject == null && rowValue != null) {
        nestedResultObjects.clear();
        storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
      }
      rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, rowKey, null, partialObject);
    } else {
      rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, rowKey, null, partialObject);
      if (partialObject == null) {
        storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
      }
    }
  }
  if (rowValue != null && mappedStatement.isResultOrdered() && shouldProcessMoreRows(resultContext, rowBounds)) {
    storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
  }
}
 
Example 15
Source Project: mybatis   Source File: BatchExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    handler.parameterize(stmt);
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 16
Source Project: mybaties   Source File: BaseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  List<E> list;
  //先向缓存中放入占位符???
  localCache.putObject(key, EXECUTION_PLACEHOLDER);
  try {
    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
  } finally {
    //最后删除占位符
    localCache.removeObject(key);
  }
  //加入缓存
  localCache.putObject(key, list);
  //如果是存储过程,OUT参数也加入缓存
  if (ms.getStatementType() == StatementType.CALLABLE) {
    localOutputParameterCache.putObject(key, parameter);
  }
  return list;
}
 
Example 17
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
  final DefaultResultContext resultContext = new DefaultResultContext();
  skipRows(rsw.getResultSet(), rowBounds);
  Object rowValue = null;
  while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
    final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
    final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
    Object partialObject = nestedResultObjects.get(rowKey);
    // issue #577 && #542
    if (mappedStatement.isResultOrdered()) {
      if (partialObject == null && rowValue != null) {
        nestedResultObjects.clear();
        storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
      }
      rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, rowKey, null, partialObject);
    } else {
      rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, rowKey, null, partialObject);
      if (partialObject == null) {
        storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
      }
    }
  }
  if (rowValue != null && mappedStatement.isResultOrdered() && shouldProcessMoreRows(resultContext, rowBounds)) {
    storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
  }
}
 
Example 18
@Test
public void shouldHandleRowBounds() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
  Date targetMonth = fmt.parse("2014-01-01");
  final List<Account> accounts = new ArrayList<Account>();
  try {
    sqlSession.select("collectPageByBirthMonth", targetMonth, new RowBounds(1, 2), new ResultHandler() {
      @Override
      public void handleResult(ResultContext context) {
        Account account = (Account) context.getResultObject();
        accounts.add(account);
      }
    });
  } finally {
    sqlSession.close();
  }
  assertEquals(2, accounts.size());
  assertEquals("Bob2", accounts.get(0).getAccountName());
  assertEquals("Bob3", accounts.get(1).getAccountName());
}
 
Example 19
Source Project: mybaties   Source File: RoutingStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    //根据语句类型,委派到不同的语句处理器(STATEMENT|PREPARED|CALLABLE)
    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }
 
Example 20
Source Project: mybaties   Source File: CachingExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
    throws SQLException {
  Cache cache = ms.getCache();
  //默认情况下是没有开启缓存的(二级缓存).要开启二级缓存,你需要在你的 SQL 映射文件中添加一行: <cache/>
  //简单的说,就是先查CacheKey,查不到再委托给实际的执行器去查
  if (cache != null) {
    flushCacheIfRequired(ms);
    if (ms.isUseCache() && resultHandler == null) {
      ensureNoOutParams(ms, parameterObject, boundSql);
      @SuppressWarnings("unchecked")
      List<E> list = (List<E>) tcm.getObject(cache, key);
      if (list == null) {
        list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
        tcm.putObject(cache, key, list); // issue #578 and #116
      }
      return list;
    }
  }
  return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
 
Example 21
Source Project: mybaties   Source File: SimpleExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    //新建一个StatementHandler
    //这里看到ResultHandler传入了
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    //准备语句
    stmt = prepareStatement(handler, ms.getStatementLog());
    //StatementHandler.query
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}
 
Example 22
Source Project: mybaties   Source File: NestedResultHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected=PersistenceException.class)
public void testUnorderedGetPersonWithHandler() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    sqlSession.select("getPersonsWithItemsOrdered", new ResultHandler() {
      public void handleResult(ResultContext context) {
        Person person = (Person) context.getResultObject();
        if ("grandma".equals(person.getName())) {
          Assert.assertEquals(2, person.getItems().size());
        }
      }
    });
  } finally {
    sqlSession.close();
  }
}
 
Example 23
@Test
public void shouldHandleRowBounds() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
  Date targetMonth = fmt.parse("2014-01-01");
  final List<Account> accounts = new ArrayList<Account>();
  try {
    sqlSession.select("collectPageByBirthMonth", targetMonth, new RowBounds(1, 2), new ResultHandler() {
      @Override
      public void handleResult(ResultContext context) {
        Account account = (Account) context.getResultObject();
        accounts.add(account);
      }
    });
  } finally {
    sqlSession.close();
  }
  assertEquals(2, accounts.size());
  assertEquals("Bob2", accounts.get(0).getAccountName());
  assertEquals("Bob3", accounts.get(1).getAccountName());
}
 
Example 24
@Test
public void shouldHandleStop() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
  final List<Account> accounts = new ArrayList<Account>();
  try {
    Date targetMonth = fmt.parse("2014-01-01");
    sqlSession.select("collectPageByBirthMonth", targetMonth, new ResultHandler() {
      @Override
      public void handleResult(ResultContext context) {
        Account account = (Account) context.getResultObject();
        accounts.add(account);
        if (accounts.size() > 1)
          context.stop();
      }
    });
  } finally {
    sqlSession.close();
  }
  assertEquals(2, accounts.size());
  assertEquals("Bob1", accounts.get(0).getAccountName());
  assertEquals("Bob2", accounts.get(1).getAccountName());
}
 
Example 25
Source Project: mybatis   Source File: SimpleStatementHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
  String sql = boundSql.getSql();
  statement.execute(sql);
  //先执行Statement.execute,然后交给ResultSetHandler.handleResultSets
  return resultSetHandler.<E>handleResultSets(statement);
}
 
Example 26
@Override
protected void findPropertiesByIds(List<Long> ids, final PropertyFinderCallback callback)
{
    ResultHandler valueResultHandler = new ResultHandler()
    {
        public void handleResult(ResultContext context)
        {
            PropertyIdQueryResult result = (PropertyIdQueryResult) context.getResultObject();
            Long id = result.getPropId();
            // Make the serializable value
            List<PropertyIdSearchRow> rows = result.getPropValues();
            Serializable value = convertPropertyIdSearchRows(rows);
            callback.handleProperty(id, value);
        }
    };
    // A row handler to roll up individual rows
    Configuration configuration = template.getConfiguration();
    RollupResultHandler rollupResultHandler = new RollupResultHandler(
            configuration,
            KEY_COLUMNS_FINDBYIDS,
            "propValues",
            valueResultHandler);
    // Query using the IDs
    PropertyIdQueryParameter params = new PropertyIdQueryParameter();
    params.setRootPropIds(ids);
    template.select(SELECT_PROPERTIES_BY_IDS, params, rollupResultHandler);
    // Process any remaining results
    rollupResultHandler.processLastResults();
    // Done
}
 
Example 27
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
    throws SQLException {
  DefaultResultContext resultContext = new DefaultResultContext();
  skipRows(rsw.getResultSet(), rowBounds);
  while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
    ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
    Object rowValue = getRowValue(rsw, discriminatedResultMap);
    storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
  }
}
 
Example 28
@Override
@SuppressWarnings("rawtypes")
public Pair<Long, Long> getNodeIdsIntervalForType(QName type, Long startTxnTime, Long endTxnTime)
{
    final Pair<Long, Long> intervalPair = new Pair<Long, Long>(LONG_ZERO, LONG_ZERO);
    Pair<Long, QName> typePair = qnameDAO.getQName(type);
    if (typePair == null)
    {
        // Return default
        return intervalPair;
    }
    TransactionQueryEntity txnQuery = new TransactionQueryEntity();
    txnQuery.setTypeQNameId(typePair.getFirst());
    txnQuery.setMinCommitTime(startTxnTime);
    txnQuery.setMaxCommitTime(endTxnTime);
    
    ResultHandler resultHandler = new ResultHandler()
    {
        @SuppressWarnings("unchecked")
        public void handleResult(ResultContext context)
        {
            Map<Long, Long> result = (Map<Long, Long>) context.getResultObject();
            if (result != null)
            {
                intervalPair.setFirst(result.get("minId"));
                intervalPair.setSecond(result.get("maxId"));
            }
        }
    };
    template.select(SELECT_NODE_INTERVAL_BY_TYPE, txnQuery, resultHandler);
    return intervalPair;
}
 
Example 29
Source Project: mybatis   Source File: CommonPropertyDeferLoadError.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferLoadDuringResultHandlerWithLazyLoad() {
    SqlSession sqlSession = lazyLoadSqlSessionFactory.openSession();
    try {
        class MyResultHandler implements ResultHandler {
            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();
    }
}
 
Example 30
Source Project: nexus-public   Source File: EntityExecutor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public <E> List<E> query(final MappedStatement ms,
                         final Object parameter,
                         final RowBounds rowBounds,
                         final ResultHandler resultHandler,
                         final CacheKey cacheKey,
                         final BoundSql boundSql)
    throws SQLException
{
  return delegate.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}