org.apache.ibatis.session.ResultHandler Java Examples

The following examples show how to use org.apache.ibatis.session.ResultHandler. 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 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 #2
Source File: SqlSessionMetricsWrapper.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #3
Source File: SqlSessionTestBase.java    From pinpoint with 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 #4
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 #5
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 #6
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 #7
Source File: RollupResultHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @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 #8
Source File: BaseStatementHandler.java    From mybatis with 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 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: PaginationHandler.java    From azeroth with 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 File: PaginationHandler.java    From jeesuite-libs with 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 File: PaginationHandler.java    From jeesuite-libs with 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 File: DefaultResultSetHandler.java    From mybatis with 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 #14
Source File: SortListInterceptor.java    From QuickProject with 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 #15
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 #16
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 #17
Source File: SimpleExecutor.java    From mybaties with 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 #18
Source File: CachingExecutor.java    From mybaties with 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 #19
Source File: RoutingStatementHandler.java    From mybaties with 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 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 #21
Source File: DefaultResultSetHandler.java    From mybaties with 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 #22
Source File: BaseExecutor.java    From mybaties with 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 #23
Source File: BatchExecutor.java    From mybatis with 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 #24
Source File: MapperMethod.java    From mybaties with 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 #25
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 #26
Source File: MapperAnnotationBuilder.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private Class<?> getParameterType(Method method) {
  Class<?> parameterType = null;
  Class<?>[] parameterTypes = method.getParameterTypes();
  for (int i = 0; i < parameterTypes.length; i++) {
    if (!RowBounds.class.isAssignableFrom(parameterTypes[i]) && !ResultHandler.class.isAssignableFrom(parameterTypes[i])) {
      if (parameterType == null) {
        parameterType = parameterTypes[i];
      } else {
        // issue #135
        parameterType = ParamMap.class;
      }
    }
  }
  return parameterType;
}
 
Example #27
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void storeObject(ResultHandler resultHandler, DefaultResultContext resultContext, Object rowValue, ResultMapping parentMapping, ResultSet rs) throws SQLException {
  if (parentMapping != null) {
    linkToParents(rs, parentMapping, rowValue);
  } else {
    callResultHandler(resultHandler, resultContext, rowValue);
  }
}
 
Example #28
Source File: BaseExecutor.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
  //如果已经关闭,报错
  if (closed) {
    throw new ExecutorException("Executor was closed.");
  }
  //先清局部缓存,再查询.但仅查询堆栈为0,才清。为了处理递归调用
  if (queryStack == 0 && ms.isFlushCacheRequired()) {
    clearLocalCache();
  }
  List<E> list;
  try {
    //加一,这样递归调用到上面的时候就不会再清局部缓存了
    queryStack++;
    //先根据cachekey从localCache去查
    list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
    if (list != null) {
      //若查到localCache缓存,处理localOutputParameterCache
      handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
    } else {
      //从数据库查
      list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
    }
  } finally {
    //清空堆栈
    queryStack--;
  }
  if (queryStack == 0) {
    //延迟加载队列中所有元素
    for (DeferredLoad deferredLoad : deferredLoads) {
      deferredLoad.load();
    }
    // issue #601
    //清空延迟加载队列
    deferredLoads.clear();
    if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
      // issue #482
  	//如果是STATEMENT,清本地缓存
      clearLocalCache();
    }
  }
  return list;
}
 
Example #29
Source File: StatementLogSqlSession.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void select(String statement, Object parameter, ResultHandler handler) {
  long start = System.currentTimeMillis();

  super.select(statement, parameter, handler);

  long duration = System.currentTimeMillis() - start;
  logStatement(SqlStatementType.SELECT, parameter, statement, duration);
}
 
Example #30
Source File: CallableStatementHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
  CallableStatement cs = (CallableStatement) statement;
  cs.execute();
  List<E> resultList = resultSetHandler.<E>handleResultSets(cs);
  resultSetHandler.handleOutputParameters(cs);
  return resultList;
}