org.apache.ibatis.session.ResultContext Java Examples

The following examples show how to use org.apache.ibatis.session.ResultContext. 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 File: NestedResultHandlerAssociationTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: NestedResultHandlerTest.java    From mybaties with 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 #3
Source File: NestedResultHandlerTest.java    From mybaties with 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 #4
Source File: NestedResultHandlerAssociationTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: NodeDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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
Source File: NodeDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #7
Source File: NodeDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #8
Source File: NestedResultHandlerAssociationTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: NestedResultHandlerTest.java    From mybatis with 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 File: NestedResultHandlerTest.java    From mybatis with 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 #11
Source File: NestedResultHandlerAssociationTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: AbstractCSVResultHandlerImpl.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void handleResult(ResultContext context) {
    if (L.isDebugEnabled()) {
        int cnt = context.getResultCount();
        L.debug(Strings.substitute(R.getString("D-CSV-MYBATIS#0001"), Maps.hash("count", Integer.valueOf(cnt))));
    }
    write(context);
}
 
Example #13
Source File: AbstractCSVResultHandlerImplTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Override
public void write(ResultContext context) {
    MobilePhone d = (MobilePhone) context.getResultObject();
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    String[] data = new String[] {
        d.getTerminalId().toString(), d.getTerminalName(), format.format(d.getSalesDate()),
        d.getFlashLevel().toString(), d.getVersion().toString()
    };
    csv.write(data);
    count.incrementAndGet();
}
 
Example #14
Source File: DefaultMapResultHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public void handleResult(ResultContext context) {
  // TODO is that assignment always true?
  //得到一条记录
  //这边黄色警告没法去掉了?因为返回Object型
  final V value = (V) context.getResultObject();
  //MetaObject.forObject,包装一下记录
  //MetaObject是用反射来包装各种类型
  final MetaObject mo = MetaObject.forObject(value, objectFactory, objectWrapperFactory);
  // TODO is that assignment always true?
  final K key = (K) mo.getValue(mapKey);
  mappedResults.put(key, value);
  //这个类主要目的是把得到的List转为Map
}
 
Example #15
Source File: CommonPropertyDeferLoadError.java    From mybatis with 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 #16
Source File: PairResultHandler.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleResult(ResultContext<? extends Object> resultContext) {
	Object object = resultContext.getResultObject();
	if (Map.class.isAssignableFrom(object.getClass())) {
		Map<String, Object> map = (Map<String, Object>) object;
		Object key = context.key.resolve(map.get("key"));
		Object value = context.value.resolve(map.get("value"));
		Pair<?, ?> pair = new Pair<>(key, value);
		many.add(pair);
	}
}
 
Example #17
Source File: CommonPropertyDeferLoadError.java    From mybaties with 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 #18
Source File: CommonPropertyDeferLoadError.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferLoadDuringResultHandler() {
    SqlSession sqlSession = sqlSessionFactory.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 #19
Source File: CommonPropertyDeferLoadError.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferLoadDuringResultHandler() {
    SqlSession sqlSession = sqlSessionFactory.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 #20
Source File: DefaultMapResultHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public void handleResult(ResultContext context) {
  // TODO is that assignment always true?
  //得到一条记录
  //这边黄色警告没法去掉了?因为返回Object型
  final V value = (V) context.getResultObject();
  //MetaObject.forObject,包装一下记录
  //MetaObject是用反射来包装各种类型
  final MetaObject mo = MetaObject.forObject(value, objectFactory, objectWrapperFactory);
  // TODO is that assignment always true?
  final K key = (K) mo.getValue(mapKey);
  mappedResults.put(key, value);
  //这个类主要目的是把得到的List转为Map
}
 
Example #21
Source File: SqlSessionMetricsWrapper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void handleResult(ResultContext resultContext)
{
    // we may never get here if the query does not return results
    if (firstTime)
    {
        // report the time only when the first row is returned form the DB
        // this report method should never throw exceptions
        reportQueryExecuted(startTime, SELECT_LABEL, statementID);
        firstTime = false;
    }
    // In the future we may be interested in summing up all the time the handler took, and report it as a metric
    handler.handleResult(resultContext);
}
 
Example #22
Source File: RollupResultHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void handleResult(ResultContext context)
{
    // Shortcut if we have processed enough results
    if (maxResults > 0 && resultCount >= maxResults)
    {
        return;
    }
    
    Object valueObject = context.getResultObject();
    MetaObject probe = configuration.newMetaObject(valueObject);
    
    // Check if the key has changed
    if (lastKeyValues == null)
    {
        lastKeyValues = getKeyValues(probe);
        resultCount = 0;
    }
    // Check if it has changed
    Object[] currentKeyValues = getKeyValues(probe);
    if (!Arrays.deepEquals(lastKeyValues, currentKeyValues))
    {
        // Key has changed, so handle the results
        Object resultObject = coalesceResults(configuration, rawResults, collectionProperty);
        if (resultObject != null)
        {
            DefaultResultContext resultContext = new DefaultResultContext();
            resultContext.nextResultObject(resultObject);
            
            resultHandler.handleResult(resultContext);
            resultCount++;
        }
        rawResults.clear();
        lastKeyValues = currentKeyValues;
    }
    // Add the new value to the results for next time
    rawResults.add(valueObject);
    // Done
}
 
Example #23
Source File: NodeDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #24
Source File: UsageDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void handleResult(ResultContext context)
{
    handler.handle((Map<String, Object>)context.getResultObject());
    total++;
    if (logger.isDebugEnabled() && (total == 0 || (total % 1000 == 0) ))
    {
        logger.debug("   Listed " + total + " map entries");
    }
}
 
Example #25
Source File: CannedQueryDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleResult(ResultContext ctx)
{
    if (stopped || ctx.isStopped())
    {
        return;             // Fly through results without further callbacks
    }
    boolean more = this.target.handleResult((R)ctx.getResultObject());
    if (!more)
    {
        ctx.stop();
        stopped = true;
    }
}
 
Example #26
Source File: PropertyValueDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 File: UserResultHandler.java    From mybaties with Apache License 2.0 4 votes vote down vote up
@Override
public void handleResult(ResultContext context) {
  User user = (User) context.getResultObject();
  users.add(user);
}
 
Example #28
Source File: UserResultHandler.java    From mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public void handleResult(ResultContext context) {
  User user = (User) context.getResultObject();
  users.add(user);
}
 
Example #29
Source File: DefaultResultHandler.java    From mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public void handleResult(ResultContext context) {
  //处理很简单,就是把记录加入List
  list.add(context.getResultObject());
}
 
Example #30
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 4 votes vote down vote up
private boolean shouldProcessMoreRows(ResultContext context, RowBounds rowBounds) throws SQLException {
  return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
}