Java 类org.apache.ibatis.session.RowBounds 实例源码

项目:cjs_ssms    文件:UserFrontServiceImpl.java   
/**
 * 分页查询
 * @param user
 * @param pageNo
 * @param limit
 * @return
 */
@Override
public Page<UUser> findByParams(UUser user, int pageNo, int limit) {
  Page<UUser> page = new Page<UUser>();
  page.setPageNo(pageNo);
  page.setLimit(limit);

  int offset = page.getOffsets();
  RowBounds rowBound = new RowBounds(offset, limit);

  List<UUser> users = userRolePermissionDao.findByParams(user,rowBound);
  page.setRows(users);
  int total = userRolePermissionDao.findAllCount(user) ;
  page.setTotal(total) ;
  if(offset >= page.getTotal()){
    page.setPageNo(page.getTotalPages());
  }
  return page ;
}
项目:cjs_ssms    文件:PageHelperTest.java   
public static void main(String[] args) throws IOException {

    SqlSession sqlSession = MybatisHelper.getSqlSession();
    CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);

    /*rowBounds*/
    RowBounds rowBounds = new RowBounds(2, 5);
    /*Example*/
    Example example = new Example(Country.class);
    Example.Criteria criteria = example.createCriteria();

//    criteria.andCountrycodeBetween("0", "ZZZZZZZZZZ");
//    criteria.andIdBetween(0, 20);

    List<Country> countries1 = countryMapper.selectByExample(example);
    log.debug("countries1" + countries1.size());
    List<Country> countries2 = countryMapper.selectByExampleAndRowBounds(example, rowBounds);
    log.debug("countries2" + countries2.size());


    PageInfo<Country> pageInfo = new PageInfo<>(countries1);
    System.out.println("PageHelperTest.main() pageInfo :" + pageInfo.getSize());

  }
项目:ipayquery    文件:PageHelper.java   
/**
 * 获取分页参数
 *
 * @param rowBounds
 *            RowBounds参数
 * @return 返回Page对象
 */
private Page getPage(RowBounds rowBounds) {
    Page page = LOCAL_PAGE.get();
    // 移除本地变量
    LOCAL_PAGE.remove();
    if (page == null) {
        if (offsetAsPageNum) {
            page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount);
        } else {
            page = new Page(rowBounds, rowBoundsWithCount);
        }
    }
    // 分页合理化
    if (page.getReasonable() == null) {
        page.setReasonable(reasonable);
    }
    // 当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
    if (page.getPageSizeZero() == null) {
        page.setPageSizeZero(pageSizeZero);
    }
    return page;
}
项目:mybatis-plus-mini    文件:MybatisMapperAnnotationBuilder.java   
private Class<?> getParameterType(Method method) {
    Class<?> parameterType = null;
    Class<?>[] parameterTypes = method.getParameterTypes();
    for (Class<?> currentParameterType : parameterTypes) {
        if (!RowBounds.class.isAssignableFrom(currentParameterType)
                && !ResultHandler.class.isAssignableFrom(currentParameterType)) {
            if (parameterType == null) {
                parameterType = currentParameterType;
            } else {
                // issue #135
                parameterType = ParamMap.class;
            }
        }
    }
    return parameterType;
}
项目:mybatis-plus-mini    文件:NoXMLTest.java   
public static void main(String[] args) {
     /*
      * 加载配置文件
*/
     InputStream in = NoXMLTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
     MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
     SqlSessionFactory sessionFactory = mf.build(in);
     SqlSession sqlSession = sessionFactory.openSession();
     /**
      * 查询是否有结果
      */
     TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
     testMapper.insert(new Test(IdWorker.getId(), "Caratacus"));
     List<Map<String, Object>> list = testMapper.selectMaps(null);
     List<Map<String, Object>> list1 = testMapper.selectMapsPage(RowBounds.DEFAULT, null);
     List<Map<String, Object>> list2 = testMapper.selectMapsPage(new Page<>(1, 5), null);
     System.out.println(list);
     System.out.println(list1);
     System.out.println(list2);
     testMapper.delete(null);

 }
项目:alfresco-repository    文件:AclCrudDAOImpl.java   
@Override
protected Long selectMaxChangeSetIdBeforeCommitTime(long maxCommitTime)
{
    Assert.notNull(maxCommitTime, "maxCommitTime");

    Map<String, Object> params = new HashMap<String, Object>(1);
    params.put("commit_time_ms", maxCommitTime);

    List<Long> sets = template.selectList(SELECT_CHANGE_SET_LAST, params, new RowBounds(0, 1));
    if (sets.size() > 0)
    {
        return sets.get(0);
    }
    else
    {
        return null;
    }
}
项目:alfresco-repository    文件:PropertyValueDAOImpl.java   
@Override
protected Long findStringValueByValue(String value)
{
    PropertyStringValueEntity entity = new PropertyStringValueEntity();
    entity.setValue(value);
    List<Long> rows = template.selectList(
            SELECT_PROPERTY_STRING_VALUE_BY_VALUE,
            entity,
            new RowBounds(0, 1));
    // The CRC match prevents incorrect results from coming back.  Although there could be
    // several matches, we are sure that the matches are case-sensitive.
    if (rows.size() > 0)
    {
        return rows.get(0);
    }
    else
    {
        return null;
    }
}
项目:alfresco-repository    文件:ActivityPostDAOImpl.java   
@SuppressWarnings("unchecked")
public List<ActivityPostEntity> selectPosts(ActivityPostEntity activityPost, int maxItems) throws SQLException 
{
    int rowLimit = maxItems < 0 ? RowBounds.NO_ROW_LIMIT : maxItems;
    RowBounds rowBounds = new RowBounds(RowBounds.NO_ROW_OFFSET, rowLimit);

    if ((activityPost.getJobTaskNode() != -1) &&
        (activityPost.getMinId() != -1) &&
        (activityPost.getMaxId() != -1) &&
        (activityPost.getStatus() != null))
    {
        return template.selectList("alfresco.activities.select_activity_posts_by_params", activityPost, rowBounds);
    }
    else if (activityPost.getStatus() != null)
    {
        return template.selectList("alfresco.activities.select_activity_posts_by_status", activityPost, rowBounds);
    }
    else
    {
        return new ArrayList<ActivityPostEntity>(0);
    }
}
项目:alfresco-repository    文件:ContentDataDAOImpl.java   
@Override
public void getContentUrlsKeepOrphaned(
        final ContentUrlHandler contentUrlHandler,
        final int maxResults)
{
    List<ContentUrlEntity> results = template.selectList(SELECT_CONTENT_URLS_KEEP_ORPHANED,
                                                                                  new RowBounds(0, maxResults));
    // Pass the result to the callback
    for (ContentUrlEntity result : results)
    {
        contentUrlHandler.handle(
                result.getId(),
                result.getContentUrl(),
                result.getOrphanTime());
    }
}
项目:alfresco-repository    文件:SOLRDAOImpl.java   
/**
    * {@inheritDoc}
    */
@Override
   @SuppressWarnings("unchecked")
   public List<AclChangeSet> getAclChangeSets(Long minAclChangeSetId, Long fromCommitTime, Long maxAclChangeSetId, Long toCommitTime, int maxResults)
   {
       if (maxResults <= 0 || maxResults == Integer.MAX_VALUE)
       {
           throw new IllegalArgumentException("Maximum results must be a reasonable number.");
       }

       // We simulate an ID for the sys:deleted type
       Pair<Long, QName> deletedTypeQNamePair = qnameDAO.getQName(ContentModel.TYPE_DELETED);
       Long deletedTypeQNameId = deletedTypeQNamePair == null ? -1L : deletedTypeQNamePair.getFirst();

       SOLRTrackingParameters params = new SOLRTrackingParameters(deletedTypeQNameId);
       params.setFromIdInclusive(minAclChangeSetId);
       params.setFromCommitTimeInclusive(fromCommitTime);
       params.setToIdExclusive(maxAclChangeSetId);
       params.setToCommitTimeExclusive(toCommitTime);

       return template.selectList(SELECT_CHANGESETS_SUMMARY, params, new RowBounds(0, maxResults));
   }
项目:alfresco-repository    文件:SOLRDAOImpl.java   
/**
    * {@inheritDoc}
    */
   @Override
   @SuppressWarnings("unchecked")
public List<Transaction> getTransactions(Long minTxnId, Long fromCommitTime, Long maxTxnId, Long toCommitTime, int maxResults)
{
       if (maxResults <= 0 || maxResults == Integer.MAX_VALUE)
       {
           throw new IllegalArgumentException("Maximum results must be a reasonable number.");
       }

       // We simulate an ID for the sys:deleted type
       Pair<Long, QName> deletedTypeQNamePair = qnameDAO.getQName(ContentModel.TYPE_DELETED);
       Long deletedTypeQNameId = deletedTypeQNamePair == null ? -1L : deletedTypeQNamePair.getFirst();

       SOLRTrackingParameters params = new SOLRTrackingParameters(deletedTypeQNameId);
    params.setFromIdInclusive(minTxnId);
    params.setFromCommitTimeInclusive(fromCommitTime);
    params.setToIdExclusive(maxTxnId);
       params.setToCommitTimeExclusive(toCommitTime);

       return template.selectList(SELECT_TRANSACTIONS, params, new RowBounds(0, maxResults));
}
项目:alfresco-repository    文件:NodeDAOImpl.java   
@SuppressWarnings("unchecked")
@Override
protected List<ChildAssocEntity> selectChildNodeIds(
        Long nodeId,
        Boolean isPrimary,
        Long minChildNodeIdInclusive,
        int maxResults)
{
    ChildAssocEntity assoc = new ChildAssocEntity();
    NodeEntity parentNode = new NodeEntity();
    parentNode.setId(nodeId);
    NodeEntity childNode = new NodeEntity();
    childNode.setId(minChildNodeIdInclusive);
    assoc.setParentNode(parentNode);
    assoc.setPrimary(isPrimary);
    assoc.setChildNode(childNode);

    RowBounds rowBounds = new RowBounds(0, maxResults);
    return template.selectList(SELECT_CHILD_NODE_IDS, assoc, rowBounds);
}
项目:alfresco-repository    文件:NodeDAOImpl.java   
@SuppressWarnings("unchecked")
@Override
protected Transaction selectLastTxnBeforeCommitTime(Long maxCommitTime)
{
    Assert.notNull(maxCommitTime, "maxCommitTime");

    TransactionQueryEntity query = new TransactionQueryEntity();
    query.setMaxCommitTime(maxCommitTime);

    List<Transaction> txns = template.selectList(SELECT_TXN_LAST, query, new RowBounds(0, 1));
    if (txns.size() > 0)
    {
        return txns.get(0);
    }
    else
    {
        return null;
    }
}
项目:alfresco-repository    文件:NodeDAOImpl.java   
@SuppressWarnings("unchecked")
@Override
protected List<Long> selectTxnsUnused(Long minTxnId, Long maxCommitTime, Integer count)
{
    TransactionQueryEntity query = new TransactionQueryEntity();
    query.setMinId(minTxnId);
    query.setMaxCommitTime(maxCommitTime);
    if (count == null)
    {
        return template.selectList(SELECT_TXNS_UNUSED, query);
    }
    else
    {
        return template.selectList(SELECT_TXNS_UNUSED, query, new RowBounds(0, count));
    }
}
项目:sns-todo    文件:TodoDetailRepository.java   
public List<SnsTodoDetailDO> list(String userName, Boolean finished, Integer pageNum, Integer pageSize) {
    SnsTodoDetailDOExample example = new SnsTodoDetailDOExample();
    SnsTodoDetailDOExample.Criteria criteria = example.createCriteria();
    criteria.andUsernameEqualTo(userName);
    if (finished != null) {
        if (finished) {
            criteria.andFinishedEqualTo(true);
        } else {
            criteria.andFinishedEqualTo(false);
        }
    }
    criteria.andStatusEqualTo(Flag.UniversalFlag.NORMAL);


    example.setOrderByClause(" weight desc,create_time desc ");

    return snsTodoDetailDOMapper.selectByExampleAndRowBounds(example, new RowBounds(pageNum, pageSize));
}
项目:dswork    文件:MyBatisDao.java   
/**
     * 分页查询数据
     * @param statementName 查询SQL的ID(不包含namespace)
     * @param pageRequest PageRequest.getFilters()查询参数和条件数据
     * @param statementNameCount 查询总数SQL的ID(不包含namespace)
     * @param pageRequestCount PageRequest.getFilters()查询参数和条件数据
     * @return Page
     */
    protected Page queryPage(String statementName, PageRequest pageRequest, String statementNameCount, PageRequest pageRequestCount)
    {
//      if (!(pageRequest.getFilters() instanceof Map))
//      {
//          Map parameterObject = BeanUtils.describe(pageRequest.getFilters());
//          pageRequest.setFilters(parameterObject);
//      }
//      if (!(countPageRequest.getFilters() instanceof Map))
//      {
//          Map parameterObject = BeanUtils.describe(countPageRequest.getFilters());
//          countPageRequest.setFilters(parameterObject);
//      }
        int totalCount = queryCount(statementNameCount, pageRequestCount);
        Page page = new Page(pageRequest.getCurrentPage(), pageRequest.getPageSize(), totalCount);
        page.setPageName(pageRequest.getPageName());
        page.setPageSizeName(pageRequest.getPageSizeName());
        // if(page.getTotalCount() <= 0){page.setResult(new ArrayList(0));}else{}//没数据的话不影响性能,而实际上又不可能没有数据
        List list = getSqlSessionTemplate().selectList(getStatementName(statementName), pageRequest.getFilters(), new RowBounds(page.getFirstResultIndex(), page.getPageSize()));
        page.setResult(list);
        return page;
    }
项目:tasfe-framework    文件:SqlUtil.java   
/**
 * 获取分页参数
 *
 * @param params RowBounds参数
 * @return 返回Page对象
 */
public PageHelper getPage(Object params) {
    PageHelper page = getLocalPage();
    if (page == null) {
        if (params instanceof RowBounds) {
            RowBounds rowBounds = (RowBounds) params;
            if (offsetAsPageNum) {
                page = new PageHelper(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount);
            } else {
                page = new PageHelper(rowBounds, rowBoundsWithCount);
            }
        } else {
            page = getPageFromObject(params);
        }
        setLocalPage(page);
    }
    //分页合理化
    if (page.getReasonable() == null) {
        page.setReasonable(reasonable);
    }
    //当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
    if (page.getPageSizeZero() == null) {
        page.setPageSizeZero(pageSizeZero);
    }
    return page;
}
项目:taskana    文件:ObjectReferenceQueryImpl.java   
@Override
public List<ObjectReference> list(int offset, int limit) {
    LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this);
    List<ObjectReference> result = null;
    try {
        taskanaEngineImpl.openConnection();
        RowBounds rowBounds = new RowBounds(offset, limit);
        result = taskanaEngineImpl.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds);
        return result;
    } finally {
        taskanaEngineImpl.returnConnection();
        if (LOGGER.isDebugEnabled()) {
            int numberOfResultObjects = result == null ? 0 : result.size();
            LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", numberOfResultObjects, LoggerUtils.listToString(result));
        }
   }
}
项目:taskana    文件:WorkbasketQueryImpl.java   
@Override
public List<WorkbasketSummary> list(int offset, int limit) {
    LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this);
    List<WorkbasketSummary> workbaskets = null;
    try {
        taskanaEngineImpl.openConnection();
        RowBounds rowBounds = new RowBounds(offset, limit);
        workbaskets = taskanaEngineImpl.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds);
        return workbaskets;
    } finally {
        taskanaEngineImpl.returnConnection();
        if (LOGGER.isDebugEnabled()) {
            int numberOfResultObjects = workbaskets == null ? 0 : workbaskets.size();
            LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", numberOfResultObjects,
                LoggerUtils.listToString(workbaskets));
        }
    }
}
项目:taskana    文件:ClassificationQueryImpl.java   
@Override
public List<ClassificationSummary> list(int offset, int limit) {
    LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this);
    List<ClassificationSummary> result = null;
    try {
        taskanaEngineImpl.openConnection();
        RowBounds rowBounds = new RowBounds(offset, limit);
        result = taskanaEngineImpl.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds);
        return result;
    } finally {
        taskanaEngineImpl.returnConnection();
        if (LOGGER.isDebugEnabled()) {
            int numberOfResultObjects = result == null ? 0 : result.size();
            LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", numberOfResultObjects,
                LoggerUtils.listToString(result));
        }
    }
}
项目:aaden-pay    文件:MyBatisDaoImpl.java   
/**
 * 
 * @param key
 * 
 * @param params
 * 
 * @param page
 * 
 * @return Page<T>
 */
public Page<T> getList(String key, Object params, Page<T> page) {
    try {
        Integer totalCounts = count(key + COUNT, params);
        // add 最大页数判断
        int pageM = maxPage(totalCounts, page.getPageSize(), page.getPageNo());
        if (pageM > 0) {
            page.setPageNo(pageM);
        } // end
        if (totalCounts != null && totalCounts.longValue() > 0) {
            List<T> list = getSqlSession().selectList(key, params,
                    new RowBounds(page.getOffset(), page.getPageSize()));
            page.setResult(list);
            page.setTotalCount(totalCounts.longValue());
        }
        return page;
    } catch (Exception e) {
        logger.error(getClass().getName() + " getList exception and key is: " + key, e);
        return null;
    }
}
项目:mybatis-generator-plugin    文件:SqlHelper.java   
/**
 * 通过Mapper接口和方法名
 * @param session
 * @param mapperInterface
 * @param methodName
 * @param args
 * @return
 */
public static String getMapperSql(SqlSession session, Class mapperInterface, String methodName, Object... args) {
    String fullMapperMethodName = mapperInterface.getCanonicalName() + "." + methodName;
    if (args == null || args.length == 0) {
        return getNamespaceSql(session, fullMapperMethodName, null);
    }
    Method method = getDeclaredMethods(mapperInterface, methodName);
    Map params = new HashMap();
    final Class<?>[] argTypes = method.getParameterTypes();
    for (int i = 0; i < argTypes.length; i++) {
        if (!RowBounds.class.isAssignableFrom(argTypes[i]) && !ResultHandler.class.isAssignableFrom(argTypes[i])) {
            String paramName = "param" + String.valueOf(params.size() + 1);
            paramName = getParamNameFromAnnotation(method, i, paramName);
            params.put(paramName, i >= args.length ? null : args[i]);
        }
    }
    if (useParameter(method, args)) {
        return getNamespaceSql(session, fullMapperMethodName, args[0]);
    }
    return getNamespaceSql(session, fullMapperMethodName, params);
}
项目:azeroth    文件:PaginationHandler.java   
@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;
}
项目:dswork    文件:MyDataDao.java   
/**
 * 分页查询数据
 * @param statementName 查询SQL的ID(不包含namespace)
 * @param pageRequest PageRequest.getFilters()查询参数和条件数据
 * @param statementNameCount 查询总数SQL的ID(包含namespace)
 * @param pageRequestCount PageRequest.getFilters()查询参数和条件数据
 * @return Page
 */
public Page queryPage(String statementName, PageRequest pageRequest, String statementNameCount, PageRequest pageRequestCount)
{
    if(DataSourceHolder.isNull()){DataSourceHolder.setSlave();}// 没有设置默认使用从库数据源
    int totalCount = queryCount(statementNameCount, pageRequestCount);
    Page page = new Page(pageRequest.getCurrentPage(), pageRequest.getPageSize(), totalCount);
    // if(page.getTotalCount() <= 0){page.setResult(new ArrayList(0));}else{}//没数据的话不影响性能,而实际上又不可能没有数据
    List list = getSqlSessionTemplate().selectList(statementName, pageRequest.getFilters(), new RowBounds(page.getFirstResultIndex(), page.getPageSize()));
    page.setResult(list);
    return page;
}
项目:mybatis-plus-mini    文件:PaginationInterceptor.java   
/**
   * Physical Pagination Interceptor for all the queries with parameter {@link org.apache.ibatis.session.RowBounds}
   */
  public Object intercept(Invocation invocation) throws Throwable {
      StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
      MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
      // 先判断是不是SELECT操作
      MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
      if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
          return invocation.proceed();
      }
      RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
      /* 不需要分页的场合 */
      if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
          return invocation.proceed();
      }
      BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
      String originalSql = boundSql.getSql();
      Connection connection = (Connection) invocation.getArgs()[0];
      DBType dbType = JdbcUtils.getDbType(connection.getMetaData().getURL());
      if (rowBounds instanceof Pagination) {
          Pagination page = (Pagination) rowBounds;
          if (page.isSearchCount()) {
              this.queryTotal(JsqlParserUtils.jsqlparserCount(originalSql), mappedStatement, boundSql, page, connection);
              if (page.getTotal() <= 0) {
                  return invocation.proceed();
              }
          }
          originalSql = DialectFactory.buildPaginationSql(page, originalSql, dbType, null);
      } else {
          // support physical Pagination for RowBounds
          originalSql = DialectFactory.buildPaginationSql(rowBounds, originalSql, dbType, null);
      }

/*
       * <p> 禁用内存分页 </p> <p> 内存分页会查询所有结果出来处理(这个很吓人的),如果结果变化频繁这个数据还会不准。</p>
 */
      metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
      metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
      metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
      return invocation.proceed();
  }
项目:xproject    文件:PaginationInterceptor.java   
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
    MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
    RowBounds rowBounds = (RowBounds)metaStatementHandler.getValue("delegate.rowBounds");
    if(rowBounds == null || rowBounds == RowBounds.DEFAULT){
        return invocation.proceed();
    }
    if(dialect == null){
        Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
        Dialect.Type databaseType = null;
        String d = configuration.getVariables().getProperty("dialect");
        if(d == null || d.trim().equals("")){
            throw new IllegalStateException("No property named with 'dialect' defined in mybatis configuration xml file.");
        }
        try {
            databaseType = Dialect.Type.valueOf(d);
        } catch (Exception e) {
            throw new IllegalStateException(String.format("No such dialect enum defined in class %s.", Dialect.Type.class));
        }

        switch (databaseType) {
            case MYSQL: // MySQL分页
                dialect = new MySQLDialect();
                break;
            case ORACLE: // Oracle分页
                dialect = new OracleDialect();
                break;
        }
        if(dialect == null){
            throw new IllegalStateException(String.format("No %s dialect found!", databaseType));
        }
    }
    String originalSql = metaStatementHandler.getValue("delegate.boundSql.sql").toString();
    metaStatementHandler.setValue("delegate.boundSql.sql", dialect.getLimitSql(originalSql, rowBounds.getOffset(), rowBounds.getLimit()));
    metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
       metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
       return invocation.proceed(); 
}
项目:alfresco-repository    文件:AclCrudDAOImpl.java   
@SuppressWarnings("unchecked")
@Override
protected List<Long> getADMNodeEntityIdsByAcl(long aclEntityId, int maxResults)
{
    if (maxResults < 0)
    {
        maxResults = RowBounds.NO_ROW_LIMIT;
    }

    Map<String, Object> params = new HashMap<String, Object>(1);
    params.put("id", aclEntityId);

    return template.selectList(SELECT_ADM_NODES_BY_ACL, params, new RowBounds(0 , maxResults));
}
项目:alfresco-repository    文件:ActivityFeedDAOImpl.java   
@SuppressWarnings("unchecked")
@Override
public List<ActivityFeedEntity> selectSiteFeedEntries(String siteId, int maxFeedSize) throws SQLException
{
    ActivityFeedQueryEntity params = new ActivityFeedQueryEntity();
    params.setSiteNetwork(siteId);

    int rowLimit = maxFeedSize < 0 ? RowBounds.NO_ROW_LIMIT : maxFeedSize;
    RowBounds rowBounds = new RowBounds(RowBounds.NO_ROW_OFFSET, rowLimit);

    // for given site
    return template.selectList("alfresco.activities.select.select_activity_feed_for_site", params, rowBounds);
}
项目:ipayquery    文件:Page.java   
public Page(RowBounds rowBounds, int total) {
    super(rowBounds.getLimit() > -1 ? rowBounds.getLimit() : 0);
    this.pageSize = rowBounds.getLimit();
    this.startRow = rowBounds.getOffset();
    // RowBounds方式默认不求count总数,如果想求count,可以修改这里为SQL_COUNT
    this.total = total;
    this.endRow = this.startRow + this.pageSize;
}
项目:alfresco-repository    文件:ContentDataDAOImpl.java   
@Override
public List<ContentUrlKeyEntity> getSymmetricKeysByMasterKeyAlias(String masterKeyAlias, long fromId, int maxResults)
{
    ContentUrlKeyEntity entity = new ContentUrlKeyEntity();
    entity.setMasterKeyAlias(masterKeyAlias);
    entity.setId(fromId);
    List<ContentUrlKeyEntity> results = template.selectList(SELECT_SYMMETRIC_KEYS_BY_MASTER_KEY, 
            entity, new RowBounds(0, maxResults));
    return results;
}
项目:alfresco-repository    文件:NodeDAOImpl.java   
@SuppressWarnings("unchecked")
@Override
protected List<Transaction> selectTxns(
        Long fromTimeInclusive,
        Long toTimeExclusive,
        Integer count,
        List<Long> includeTxnIds,
        List<Long> excludeTxnIds,
        Long excludeServerId,
        Boolean ascending)
{
    TransactionQueryEntity query = new TransactionQueryEntity();
    query.setMinCommitTime(fromTimeInclusive);
    query.setMaxCommitTime(toTimeExclusive);

    if ((includeTxnIds != null) && (includeTxnIds.size() > 0))
    { 
        query.setIncludeTxnIds(includeTxnIds);
    }

    if ((excludeTxnIds != null) && (excludeTxnIds.size() > 0))
    {
        query.setExcludeTxnIds(excludeTxnIds);
    }

    query.setExcludeServerId(excludeServerId);
    query.setAscending(ascending);

    if (count == null)
    {
        return template.selectList(SELECT_TXNS, query);
    }
    else
    {
        return template.selectList(SELECT_TXNS, query, new RowBounds(0, count));
    }
}
项目:pingguopai    文件:AbstractServiceImpl.java   
@Override
public List<T> selectByPage(Condition condition, PageSO page) {
    RowBounds rowBounds = new RowBounds((page.getPageNum() -1) * page.getPageSize(),
            page.getPageSize());
    List<T> list = mapper.selectByExampleAndRowBounds(condition, rowBounds);
    return list;
}
项目:MybatisGeneatorUtil    文件:TestSelectRowBounds.java   
@Test
public void testSelectByExample() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        Example example = new Example(Country.class);
        example.createCriteria().andGreaterThan("id", 100).andLessThan("id", 151);
        example.or().andLessThan("id", 41);
        List<Country> countries = mapper.selectByExampleAndRowBounds(example, new RowBounds(10, 20));
        //查询总数
        Assert.assertEquals(20, countries.size());
    } finally {
        sqlSession.close();
    }
}
项目:tk-mybatis    文件:TestSelectRowBounds.java   
@Test
public void testSelectByExample() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        Example example = new Example(Country.class);
        example.createCriteria().andGreaterThan("id", 100).andLessThan("id", 151);
        example.or().andLessThan("id", 41);
        List<Country> countries = mapper.selectByExampleAndRowBounds(example, new RowBounds(10, 20));
        //查询总数
        Assert.assertEquals(20, countries.size());
    } finally {
        sqlSession.close();
    }
}
项目:tasfe-framework    文件:PageHelper.java   
public PageHelper(RowBounds rowBounds, int total) {
    super(rowBounds.getLimit() > -1 ? rowBounds.getLimit() : 0);
    this.pageSize = rowBounds.getLimit();
    this.startRow = rowBounds.getOffset();
    //RowBounds方式默认不求count总数,如果想求count,可以修改这里为SQL_COUNT
    this.total = total;
    this.endRow = this.startRow + this.pageSize;
}
项目:taskana    文件:TaskQueryImpl.java   
@Override
public List<Task> list(int offset, int limit) throws NotAuthorizedException {
    LOGGER.debug("entry to list(offset = {}, limit = {}), this = {}", offset, limit, this);
    List<Task> result = new ArrayList<>();
    try {
        taskanaEngineImpl.openConnection();
        checkAuthorization();
        RowBounds rowBounds = new RowBounds(offset, limit);
        List<TaskImpl> tasks = taskanaEngineImpl.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds);
        for (TaskImpl taskImpl : tasks) {
            try {
                Classification classification = this.classificationService.getClassificationByTask(taskImpl);
                taskImpl.setClassification(classification);
            } catch (ClassificationNotFoundException e) {
                throw new SystemException(
                    this.toString() + " failed to find a classification for task " + taskImpl);
            }
            result.add(taskImpl);
        }
        return result;
    } finally {
        taskanaEngineImpl.returnConnection();
        if (LOGGER.isDebugEnabled()) {
            int numberOfResultObjects = result == null ? 0 : result.size();
            LOGGER.debug("exit from list(offset,limit). Returning {} resulting Objects: {} ", numberOfResultObjects,
                LoggerUtils.listToString(result));
        }
    }
}
项目:aaden-pay    文件:PagePluging.java   
void processIntercept(final Object[] queryArgs) {
    MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
    Object parameter = queryArgs[PARAMETER_INDEX];
    final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];
    int offset = rowBounds.getOffset();
    int limit = rowBounds.getLimit();
    if (dialect.supportsLimit() && (offset != RowBounds.NO_ROW_OFFSET || limit != RowBounds.NO_ROW_LIMIT)) {
        BoundSql boundSql = ms.getBoundSql(parameter);
        String sql = boundSql.getSql().trim();
        if (dialect.supportsLimitOffset()) {
            sql = dialect.getLimitString(sql, offset, limit);
            offset = RowBounds.NO_ROW_OFFSET;
        } else {
            sql = dialect.getLimitString(sql, 0, limit);
        }
        limit = RowBounds.NO_ROW_LIMIT;
        queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit);
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(),
                boundSql.getParameterObject());
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
        queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
    }
}
项目:asura    文件:PageBounds.java   
public PageBounds(RowBounds rowBounds) {
    if(rowBounds instanceof PageBounds){
        PageBounds pageBounds = (PageBounds)rowBounds;
        this.page = pageBounds.page;
        this.limit = pageBounds.limit;
        this.orders = pageBounds.orders;
        this.containsTotalCount = pageBounds.containsTotalCount;
        this.asyncTotalCount = pageBounds.asyncTotalCount;
    }else{
        this.page = (rowBounds.getOffset()/rowBounds.getLimit())+1;
        this.limit = rowBounds.getLimit();
    }

}
项目:alfresco-audit    文件:PropertyTablesCleanupDAOImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public List<Long> listPropertyRootIds(final int maxItems, final Long fromIdExclusive)
{
    final RowBounds rowBounds = new RowBounds(0, maxItems);
    final CleanupQueryBoundsParam queryBoundsParam = new CleanupQueryBoundsParam();
    queryBoundsParam.setFromId(fromIdExclusive);
    queryBoundsParam.setMaxItems(Integer.valueOf(maxItems));

    final List<Long> ids = this.sqlSessionTemplate.selectList(SELECT_EXISTING_PROPERTY_ROOT_IDS, queryBoundsParam, rowBounds);
    LOGGER.debug("Selected {} alf_prop_root IDs starting with exclusive from ID {} and {} max items: {}", ids.size(), fromIdExclusive,
            maxItems);
    LOGGER.trace("Retrieved alf_prop_root entries : {}", ids);
    return ids;
}
项目:alfresco-audit    文件:PropertyTablesCleanupDAOImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public List<Long> listPropertyValueIds(final int maxItems, final Long fromIdExclusive)
{
    final RowBounds rowBounds = new RowBounds(0, maxItems);
    final CleanupQueryBoundsParam queryBoundsParam = new CleanupQueryBoundsParam();
    queryBoundsParam.setFromId(fromIdExclusive);
    queryBoundsParam.setMaxItems(Integer.valueOf(maxItems));

    final List<Long> ids = this.sqlSessionTemplate.selectList(SELECT_EXISTING_PROPERTY_VALUE_IDS, queryBoundsParam, rowBounds);
    LOGGER.debug("Selected {} alf_prop_value IDs starting with exclusive from ID {} and {} max items: {}", ids.size(), fromIdExclusive,
            maxItems);
    LOGGER.trace("Retrieved alf_prop_value entries:", ids);
    return ids;
}