org.apache.ibatis.session.RowBounds Java Examples

The following examples show how to use org.apache.ibatis.session.RowBounds. 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 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 #2
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 #3
Source File: BasicTest.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@Test
public void testNamespace1() {
    SqlSession sqlSession = MybatisRowBoundsHelper.getSqlSession();
    try {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = new User();
        user.setName("刘睿");
        map.put("user", user);
        //同时测试不可变Map
        map = Collections.unmodifiableMap(map);
        List<User> list = sqlSession.selectList("select1", map, new RowBounds(1, 10));
        assertEquals(1, list.size());
        //判断查询结果的位置是否正确
        assertEquals(78, list.get(0).getId());
    } finally {
        sqlSession.close();
    }
}
 
Example #4
Source File: BlogController.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@ResponseBody
@GetMapping("/blog")
public String rowBounds() {
	int pageSize = 10;
	int totalCount = blogRepository.countBlogs();
	int totalPages = (totalCount % pageSize == 0) ? totalCount / pageSize : totalCount / pageSize + 1;
	System.out.println("[pageSize=" + pageSize + ",totalCount=" + totalCount + ",totalPages=" + totalPages + "]");
	for (int currentPage = 0; currentPage < totalPages; currentPage++) {
		List<Blog> blogs = blogRepository.selectBlogs("zhaohui", new RowBounds(currentPage * pageSize, pageSize));
		System.err.println("currentPage=" + (currentPage + 1) + ",current size:" + blogs.size());
		for(Blog blog:blogs){
			System.out.println(blog);
		}
	}
	return "ok";
}
 
Example #5
Source File: MapperMethod.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
  List<E> result;
  Object param = method.convertArgsToSqlCommandParam(args);
  //代入RowBounds
  if (method.hasRowBounds()) {
    RowBounds rowBounds = method.extractRowBounds(args);
    result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
  } else {
    result = sqlSession.<E>selectList(command.getName(), param);
  }
  // issue #510 Collections & arrays support
  if (!method.getReturnType().isAssignableFrom(result.getClass())) {
    if (method.getReturnType().isArray()) {
      return convertToArray(result);
    } else {
      return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
    }
  }
  return result;
}
 
Example #6
Source File: BatchExecutor.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  final Configuration configuration = ms.getConfiguration();
  final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  final BoundSql boundSql = handler.getBoundSql();
  final String sql = boundSql.getSql();
  final Statement stmt;
  if (sql.equals(currentSql) && ms.equals(currentStatement)) {
    int last = statementList.size() - 1;
    stmt = statementList.get(last);
    BatchResult batchResult = batchResultList.get(last);
    batchResult.addParameterObject(parameterObject);
  } else {
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    currentSql = sql;
    currentStatement = ms;
    statementList.add(stmt);
    batchResultList.add(new BatchResult(ms, sql, parameterObject));
  }
  handler.parameterize(stmt);
  handler.batch(stmt);
  return BATCH_UPDATE_RETURN_VALUE;
}
 
Example #7
Source File: CachingExecutor.java    From mybatis 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 #8
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSelectDiscriminatedPost() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectDiscriminatedPost(config);
    List<Map<String,String>> products = executor.query(selectStatement, null, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    assertEquals(5, products.size());
    for (Map<String,String> m : products) {
      if ("IMAGES".equals(m.get("SECTION"))) {
        assertNull(m.get("subject"));
      } else {
        assertNotNull(m.get("subject"));
      }
    }
  } finally {
    executor.close(false);
  }
}
 
Example #9
Source File: BaseExecutor.java    From mybatis 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 #10
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMapConstructorResults() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectOneAuthorMappedStatementWithConstructorResults(config);
    List<Author> authors = executor.query(selectStatement, 102, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    executor.rollback(true);
    assertEquals(1, authors.size());

    Author author = authors.get(0);
    assertEquals(102, author.getId());
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #11
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertNewAuthorUsingSimpleNonPreparedStatements() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    Author author = new Author(99, "someone", "******", "[email protected]", null, null);
    MappedStatement insertStatement = ExecutorTestHelper.createInsertAuthorWithIDof99MappedStatement(config);
    MappedStatement selectStatement = ExecutorTestHelper.createSelectAuthorWithIDof99MappedStatement(config);
    int rows = executor.update(insertStatement, null);
    List<Author> authors = executor.query(selectStatement, 99, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    executor.rollback(true);
    assertEquals(1, authors.size());
    assertEquals(author.toString(), authors.get(0).toString());
    assertTrue(1 == rows || BatchExecutor.BATCH_UPDATE_RETURN_VALUE == rows);
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #12
Source File: SundialInterceptor.java    From Milkomeda with MIT License 6 votes vote down vote up
private void updateSql(String sql, Invocation invocation, MappedStatement ms, Object[] args, BoundSql boundSql) {
    BoundSql boundSqlNew = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    MappedStatement mappedStatement = copyFrom(ms, new BoundSqlSqlSource(boundSqlNew));
    // 替换映射的语句
    args[0] = mappedStatement;

    // 针对查询方式的参数替换
    if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
        Executor executor = (Executor) invocation.getTarget();
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        // 6个参数时(因为分页插件的原因导致问题,需要修改对应的类型值)
        if (args.length == 6) {
            args[4] = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            args[5] = boundSqlNew;
        }
    }
}
 
Example #13
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertNewAuthorWithBeforeAutoKey() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    Author author = new Author(-1, "someone", "******", "[email protected]", null, Section.NEWS);
    MappedStatement insertStatement = ExecutorTestHelper.prepareInsertAuthorMappedStatementWithBeforeAutoKey(config);
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectOneAuthorMappedStatement(config);
    int rows = executor.update(insertStatement, author);
    assertTrue(rows > 0 || rows == BatchExecutor.BATCH_UPDATE_RETURN_VALUE);
    if (rows == BatchExecutor.BATCH_UPDATE_RETURN_VALUE) {
      executor.flushStatements();
    }
    assertEquals(123456, author.getId());
    if (author.getId() != BatchExecutor.BATCH_UPDATE_RETURN_VALUE) {
      List<Author> authors = executor.query(selectStatement, author.getId(), RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
      executor.rollback(true);
      assertEquals(1, authors.size());
      assertEquals(author.toString(), authors.get(0).toString());
      assertTrue(author.getId() >= 10000);
    }
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #14
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSelectTwoSetsOfAuthorsViaProc() throws Exception {
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectTwoSetsOfAuthorsProc(config);
    List<List<Author>> authorSets = executor.query(selectStatement, new HashMap<String, Object>() {
      {
        put("id1", 101);
        put("id2", 102);
      }
    }, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    assertEquals(2, authorSets.size());
    for (List<Author> authors : authorSets) {
      assertEquals(2, authors.size());
      for (Object author : authors) {
        assertTrue(author instanceof Author);
      }
    }
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #15
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 #16
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFetchPostWithBlogWithCompositeKey() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectBlog = ExecutorTestHelper.prepareSelectBlogByIdAndAuthor(config);
    MappedStatement selectPost = ExecutorTestHelper.prepareSelectPostWithBlogByAuthorMappedStatement(config);
    config.addMappedStatement(selectBlog);
    config.addMappedStatement(selectPost);
    List<Post> posts = executor.query(selectPost, 2, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    assertEquals(1, posts.size());
    Post post = posts.get(0);
    assertNotNull(post.getBlog());
    assertEquals(101, post.getBlog().getAuthor().getId());
    executor.rollback(true);
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #17
Source File: RowBoundsTest.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
/**
 * 使用Mapper接口调用时,使用PageHelper.startPage效果更好,不需要添加Mapper接口参数
 */
@Test
public void testWithRowboundsAndCountTrue() {
    SqlSession sqlSession = MybatisRowBoundsHelper.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    try {
        //limit=0,这时候相当于用分页插件求count,但是前提必须是配置rounbounds方式求count,否则都是-1
        //这里由于没有配置,应该都是-1
        List<User> list = userMapper.selectAll(new RowBounds(1, -1));
        PageInfo<User> page = new PageInfo<User>(list);
        assertEquals(0, list.size());
        assertEquals(183, page.getTotal());

        //pageSize<0的时候同上
        list = userMapper.selectAll(new RowBounds(1, -100));
        page = new PageInfo<User>(list);
        assertEquals(0, list.size());
        assertEquals(183, page.getTotal());
    } finally {
        sqlSession.close();
    }
}
 
Example #18
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFetchOneOrphanedPostWithNoBlog() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectBlog = ExecutorTestHelper.prepareComplexSelectBlogMappedStatement(config);
    MappedStatement selectPost = ExecutorTestHelper.prepareSelectPostMappedStatement(config);
    config.addMappedStatement(selectBlog);
    config.addMappedStatement(selectPost);
    List<Post> posts = executor.query(selectPost, 5, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    executor.rollback(true);
    assertEquals(1, posts.size());
    Post post = posts.get(0);
    assertNull(post.getBlog());
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #19
Source File: ContentDataDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void getContentUrlsOrphaned(
        final ContentUrlHandler contentUrlHandler,
        final Long maxOrphanTimeExclusive,
        final int maxResults)
{
    ParameterCheck.mandatory("maxOrphanTimeExclusive", maxOrphanTimeExclusive);
    
    ContentUrlOrphanQuery query = new ContentUrlOrphanQuery();
    query.setMaxOrphanTimeExclusive(maxOrphanTimeExclusive);
    List<ContentUrlEntity> results = template.selectList(SELECT_CONTENT_URLS_ORPHANED, 
                                                                                  query, 
                                                                                  new RowBounds(0, maxResults));
    // Pass the result to the callback
    for (ContentUrlEntity result : results)
    {
        contentUrlHandler.handle(
                result.getId(),
                result.getContentUrl(),
                result.getOrphanTime());
    }
}
 
Example #20
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUpdateAuthor() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    Author author = new Author(101, "someone", "******", "[email protected]", null, Section.NEWS);
    MappedStatement updateStatement = ExecutorTestHelper.prepareUpdateAuthorMappedStatement(config);
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectOneAuthorMappedStatement(config);
    int rows = executor.update(updateStatement, author);
    List<Author> authors = executor.query(selectStatement, 101, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    executor.rollback(true);
    assertEquals(1, authors.size());
    assertEquals(author.toString(), authors.get(0).toString());
    assertTrue(1 == rows || BatchExecutor.BATCH_UPDATE_RETURN_VALUE == rows);
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #21
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertNewAuthorByProc() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    Author author = new Author(97, "someone", "******", "[email protected]", null, null);
    MappedStatement insertStatement = ExecutorTestHelper.prepareInsertAuthorProc(config);
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectOneAuthorMappedStatement(config);
    int rows = executor.update(insertStatement, author);
    List<Author> authors = executor.query(selectStatement, 97, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    executor.rollback(true);
    assertEquals(1, authors.size());
    assertEquals(author.toString(), authors.get(0).toString());
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #22
Source File: PaginationInterceptor.java    From Mario with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

    StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
    BoundSql boundSql = statementHandler.getBoundSql();

    String sql = boundSql.getSql();
    if (StringUtils.isBlank(sql)) {
        return invocation.proceed();
    }

    //select sql do 
    if (sql.matches(SQL_SELECT_REGEX) && !Pattern.matches(SQL_COUNT_REGEX, sql)) {
        Object obj = FieldUtils.readField(statementHandler, "delegate", true);
        // 反射获取 RowBounds 对象。
        RowBounds rowBounds = (RowBounds) FieldUtils.readField(obj, "rowBounds", true);

        // 分页参数存在且不为默认值时进行分页SQL构造
        if (rowBounds != null && rowBounds != RowBounds.DEFAULT) {
            FieldUtils.writeField(boundSql, "sql", newSql(sql, rowBounds), true);

            // 一定要还原否则将无法得到下一组数据(第一次的数据被缓存了)
            FieldUtils.writeField(rowBounds, "offset", RowBounds.NO_ROW_OFFSET, true);
            FieldUtils.writeField(rowBounds, "limit", RowBounds.NO_ROW_LIMIT, true);
        }
    }

    return invocation.proceed();
}
 
Example #23
Source File: DuplicateStatementsTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetFirstFourUsers() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    List<User> users = mapper.getAllUsers(new RowBounds(0, 4));
    Assert.assertEquals(4, users.size());
  } finally {
    sqlSession.close();
  }
}
 
Example #24
Source File: MapperMethod.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void executeWithResultHandler(SqlSession sqlSession, Object[] args) {
  MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(command.getName());
  if (void.class.equals(ms.getResultMaps().get(0).getType())) {
    throw new BindingException("method " + command.getName() 
        + " needs either a @ResultMap annotation, a @ResultType annotation," 
        + " or a resultType attribute in XML so a ResultHandler can be used as a parameter.");
  }
  Object param = method.convertArgsToSqlCommandParam(args);
  if (method.hasRowBounds()) {
    RowBounds rowBounds = method.extractRowBounds(args);
    sqlSession.select(command.getName(), param, rowBounds, method.extractResultHandler(args));
  } else {
    sqlSession.select(command.getName(), param, method.extractResultHandler(args));
  }
}
 
Example #25
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void handleRefCursorOutputParameter(ResultSet rs, ParameterMapping parameterMapping, MetaObject metaParam) throws SQLException {
  try {
    final String resultMapId = parameterMapping.getResultMapId();
    final ResultMap resultMap = configuration.getResultMap(resultMapId);
    final DefaultResultHandler resultHandler = new DefaultResultHandler(objectFactory);
    final ResultSetWrapper rsw = new ResultSetWrapper(rs, configuration);
    //里面就和一般ResultSet处理没两样了
    handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
    metaParam.setValue(parameterMapping.getProperty(), resultHandler.getResultList());
  } finally {
    // issue #228 (close resultsets)
    closeResultSet(rs);
  }
}
 
Example #26
Source File: BindingTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSelectListOfPostsLike() {
  SqlSession session = sqlSessionFactory.openSession();
  try {
    BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class);
    List<Post> posts = mapper.selectPostsLike(new RowBounds(1,1),"%a%");
    assertEquals(1, posts.size());
  } finally {
    session.close();
  }
}
 
Example #27
Source File: AbstractHelperDialect.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Override
public boolean afterCount(long count, Object parameterObject, RowBounds rowBounds) {
    Page page = getLocalPage();
    page.setTotal(count);
    if (rowBounds instanceof PageRowBounds) {
        ((PageRowBounds) rowBounds).setTotal(count);
    }
    //pageSize < 0 的时候,不执行分页查询
    //pageSize = 0 的时候,还需要执行后续查询,但是不会分页
    if (page.getPageSize() < 0) {
        return false;
    }
    return count > ((page.getPageNum() - 1) * page.getPageSize());
}
 
Example #28
Source File: DefaultSqlSession.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
  //转而去调用selectList
  final List<?> list = selectList(statement, parameter, rowBounds);
  final DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler<K, V>(mapKey,
      configuration.getObjectFactory(), configuration.getObjectWrapperFactory());
  final DefaultResultContext context = new DefaultResultContext();
  for (Object o : list) {
    //循环用DefaultMapResultHandler处理每条记录
    context.nextResultObject(o);
    mapResultHandler.handleResult(context);
  }
  //注意这个DefaultMapResultHandler里面存了所有已处理的记录(内部实现可能就是一个Map),最后再返回一个Map
  return mapResultHandler.getMappedResults();
}
 
Example #29
Source File: BasicTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Test
public void testNamespace3() {
    SqlSession sqlSession = MybatisRowBoundsHelper.getSqlSession();
    try {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = new User();
        map.put("user", user);
        //同时测试不可变Map
        map = Collections.unmodifiableMap(map);
        List<User> list = sqlSession.selectList("select1", map, new RowBounds(1, 10));
        assertEquals(10, list.size());
        //判断查询结果的位置是否正确
        assertEquals(1, list.get(0).getId());

        map = new HashMap<String, Object>();
        user = new User();
        user.setName("刘睿");
        map.put("user", user);
        //同时测试不可变Map
        map = Collections.unmodifiableMap(map);
        list = sqlSession.selectList("select1", map, new RowBounds(1, 10));
        assertEquals(1, list.size());
        //判断查询结果的位置是否正确
        assertEquals(78, list.get(0).getId());
    } finally {
        sqlSession.close();
    }
}
 
Example #30
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void skipRows(ResultSet rs, RowBounds rowBounds) throws SQLException {
  if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
    if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
      rs.absolute(rowBounds.getOffset());
    }
  } else {
    for (int i = 0; i < rowBounds.getOffset(); i++) {
      rs.next();
    }
  }
}