Java Code Examples for org.springframework.data.domain.Pageable#getPageSize()

The following examples show how to use org.springframework.data.domain.Pageable#getPageSize() . 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: SqlSessionRepositorySupport.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate total mount.
 * @return if return -1 means can not judge ,need count from database.
 */
protected <X> long calculateTotal(Pageable pager, List<X> result) {
	if (pager.hasPrevious()) {
		if (CollectionUtils.isEmpty(result)) {
			return -1;
		}
		if (result.size() == pager.getPageSize()) {
			return -1;
		}
		return (pager.getPageNumber() - 1) * pager.getPageSize() + result.size();
	}
	if (result.size() < pager.getPageSize()) {
		return result.size();
	}
	return -1;
}
 
Example 2
Source File: AggregateQueryProvider.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
private void addPageableStages(List<Annotation> unwoundAnnotations) {
  // if this annotation is pageable - add a facet.
  if(isPageable()) {
    Pageable pageable = mongoParameterAccessor.getPageable();

    Annotation pageableFacet = new PageableFacet(unwoundAnnotations.size(),
                                                 (int) pageable.getOffset(),
                                                 pageable.getPageSize());
    Annotation pageableUnwind = new PageableUnwind(unwoundAnnotations.size() + 1);
    Annotation pageableProject = new PageableProject(unwoundAnnotations.size() + 2);

    unwoundAnnotations.addAll(Arrays.asList(pageableFacet, pageableUnwind, pageableProject));
    int outStageIndex = getOutPipelineStageIndex(unwoundAnnotations);
    if (outStageIndex >= 0) {
      Annotation outAnnotation = unwoundAnnotations.remove(outStageIndex);
      unwoundAnnotations.add(outAnnotation);
    }
  }
}
 
Example 3
Source File: PageableMethodArgumentResolver.java    From es with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    PageableDefaults pageableDefaults = getPageableDefaults(parameter);
    //默认的page request
    Pageable defaultPageRequest = getDefaultFromAnnotationOrFallback(pageableDefaults);

    String pageableNamePrefix = getPagePrefix(parameter);
    String sortNamePrefix = getSortPrefix(parameter);
    Map<String, String[]> pageableMap = getPrefixParameterMap(pageableNamePrefix, webRequest, true);
    Map<String, String[]> sortMap = getPrefixParameterMap(sortNamePrefix, webRequest, false);

    Sort sort = getSort(sortNamePrefix, sortMap, defaultPageRequest, webRequest);
    if (pageableMap.size() == 0) {
        return new PageRequest(defaultPageRequest.getPageNumber(), defaultPageRequest.getPageSize(), sort == null ? defaultPageRequest.getSort() : sort);
    }

    int pn = getPn(pageableMap, defaultPageRequest);
    int pageSize = getPageSize(pageableMap, defaultPageRequest);

    return new PageRequest(pn - 1, pageSize, sort);

}
 
Example 4
Source File: SysRedisController.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取所有key
 * @param pageable
 * @return
 */
@GetMapping
public R getAllByPage(Pageable pageable) {
    List<RedisVo> redisList = redisUtil.getAll();
    int totalElements = redisList.size();
    if (pageable == null) {
        pageable = PageRequest.of(0, 10);
    }
    int fromIndex = pageable.getPageSize() * pageable.getPageNumber();
    int toIndex = pageable.getPageSize() * (pageable.getPageNumber() + 1);
    if (toIndex > totalElements) {
        toIndex = totalElements;
    }
    List<RedisVo> indexObjects = redisList.subList(fromIndex, toIndex);
    Page<RedisVo> page = new PageImpl<>(indexObjects, pageable, totalElements);
    return R.ok(page);
}
 
Example 5
Source File: BookService.java    From tutorials with MIT License 6 votes vote down vote up
public Page<Book> findPaginated(Pageable pageable) {
    int pageSize = pageable.getPageSize();
    int currentPage = pageable.getPageNumber();
    int startItem = currentPage * pageSize;
    List<Book> list;

    if (books.size() < startItem) {
        list = Collections.emptyList();
    } else {
        int toIndex = Math.min(startItem + pageSize, books.size());
        list = books.subList(startItem, toIndex);
    }

    Page<Book> bookPage = new PageImpl<Book>(list, PageRequest.of(currentPage, pageSize), books.size());

    return bookPage;

}
 
Example 6
Source File: DatasRepository.java    From blog with MIT License 6 votes vote down vote up
@Override
public Page<Person> findAll(Pageable arg0) {
	int pSize = arg0.getPageSize();
	int pNumb = arg0.getPageNumber();
	int pFirst = pNumb * pSize;
	int pLast = pFirst + pSize;
	int total = datas.size();
	List<Person> content = new ArrayList<>();
	for (int i = 0; i < total; i++) {
		if (i >= pFirst && i < pLast) {
			Person data = datas.get(i);
			content.add(data);
		}
	}
	return new PageImpl<>(content, arg0, total);
}
 
Example 7
Source File: AbstractSolrQuery.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(Query query) {

	Pageable pageToUse = getPageable();

	if (isLimiting()) {

		int limit = getLimit();
		if (pageToUse == null) {
			pageToUse = new SolrPageRequest(0, limit);
		}

		if (limit > 0) {
			if (pageToUse.getOffset() > limit) {
				return new PageImpl(java.util.Collections.emptyList(), pageToUse, limit);
			}
			if (pageToUse.getOffset() + pageToUse.getPageSize() > limit) {
				pageToUse = getLimitingPageable(pageToUse, limit - pageToUse.getOffset());
			}
		}
	}

	query.setPageRequest(pageToUse);
	return executeFind(query);
}
 
Example 8
Source File: AbstractSolrQuery.java    From dubbox with Apache License 2.0 6 votes vote down vote up
protected Pageable getLimitingPageable(final Pageable source, final int limit) {

		if (source == null) {
			return new SolrPageRequest(0, limit);
		}

		return new PageRequest(source.getPageNumber(), source.getPageSize(), source.getSort()) {

			private static final long serialVersionUID = 8100166028148948968L;

			@Override
			public int getOffset() {
				return source.getOffset();
			}

			@Override
			public int getPageSize() {
				return limit;
			}

		};
	}
 
Example 9
Source File: HazelcastPartTreeQuery.java    From spring-data-hazelcast with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Slices and pages are similar ways to iterate through the result set in blocks, mimicking a cursor. A
 * {@link org.springframework.data.domain.Slice Slice} is a simpler concept, only requiring to know if further blocks
 * of data are available. A {@link org.springframework.data.domain.Page Page} requires to know how many blocks of data
 * are available in total.
 * </P>
 *
 * @param parameters  For the query
 * @param query       The query to run
 * @param queryMethod Holds metadata about the query
 * @return Query result
 */
@SuppressWarnings({"rawtypes", "unchecked"})
private Object executePageSliceQuery(final Object[] parameters, final KeyValueQuery<?> query, final QueryMethod queryMethod) {
    long totalElements = -1;

    int indexOfPageRequest = queryMethod.getParameters().getPageableIndex();
    Pageable pageRequest = (Pageable) parameters[indexOfPageRequest];

    /* TODO Eliminate count call for Slice, retrieve "rows+1" instead to determine if next page exists.
     */
    if (query.getCriteria() == null) {
        totalElements = this.keyValueOperations.count(queryMethod.getEntityInformation().getJavaType());
    } else {
        totalElements = this.keyValueOperations.count(query, queryMethod.getEntityInformation().getJavaType());
    }

    int requiredRows = pageRequest.getPageSize();

    query.setOffset(pageRequest.getOffset());
    query.setRows(pageRequest.getPageSize());

    Iterable<?> resultSet = this.keyValueOperations.find(query, queryMethod.getEntityInformation().getJavaType());
    List<?> content = IterableConverter.toList(resultSet);

    if (queryMethod.isPageQuery()) {
        return new PageImpl(content, pageRequest, totalElements);
    } else {
        boolean hasNext = totalElements > (query.getOffset() + query.getRows());
        if (content.size() > requiredRows) {
            content = content.subList(0, requiredRows);
        }
        return new SliceImpl(content, pageRequest, hasNext);
    }
}
 
Example 10
Source File: TopicResource.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
/**
 * GET  /topics -> get all the topics.
 */
@RequestMapping(value = "/topics",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Topic>> getAllTopics(Pageable pageable)
    throws URISyntaxException {
    Pageable pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "weight");
    Page<Topic> page = topicRepository.findAll(pageRequest);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/topics");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 11
Source File: TagResource.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
/**
 * GET  /admin/tags -> get all the tags.
 */
@RequestMapping(value = "/admin/tags",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<Tag>> getAllTags(Pageable pageable)
    throws URISyntaxException {
    Pageable pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "id");
    Page<Tag> page = tagRepository.findAll(pageRequest);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/admin/tags");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 12
Source File: SimpleQuery.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * @param criteria
 * @param pageable
 */
public SimpleQuery(Criteria criteria, Pageable pageable) {
	super(criteria);

	if (pageable != null) {
		this.offset = pageable.getOffset();
		this.rows = pageable.getPageSize();
		this.addSort(pageable.getSort());
	}
}
 
Example 13
Source File: BaseCommentServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Page<BaseCommentVO> pageVosBy(List<COMMENT> comments, Pageable pageable) {
    Assert.notNull(comments, "Comments must not be null");
    Assert.notNull(pageable, "Page info must not be null");

    Comparator<BaseCommentVO> commentComparator = buildCommentComparator(pageable.getSortOr(Sort.by(Sort.Direction.DESC, "createTime")));

    // Convert to vo
    List<BaseCommentVO> topComments = convertToVo(comments, commentComparator);

    List<BaseCommentVO> pageContent;

    // Calc the shear index
    int startIndex = pageable.getPageNumber() * pageable.getPageSize();
    if (startIndex >= topComments.size() || startIndex < 0) {
        pageContent = Collections.emptyList();
    } else {
        int endIndex = startIndex + pageable.getPageSize();
        if (endIndex > topComments.size()) {
            endIndex = topComments.size();
        }

        log.debug("Top comments size: [{}]", topComments.size());
        log.debug("Start index: [{}]", startIndex);
        log.debug("End index: [{}]", endIndex);

        pageContent = topComments.subList(startIndex, endIndex);
    }

    return new CommentPage<>(pageContent, pageable, topComments.size(), comments.size());
}
 
Example 14
Source File: PageableAdapter.java    From springlets with Apache License 2.0 5 votes vote down vote up
@Override
public PageRequestDto marshal(Pageable request) {

  PageRequestDto dto = new PageRequestDto();
  dto.orders = request.getSort() == null ? Collections.<OrderDto>emptyList()
      : SpringDataJaxb.marshal(request.getSort(), OrderAdapter.INSTANCE);
  dto.page = request.getPageNumber();
  dto.size = request.getPageSize();

  return dto;
}
 
Example 15
Source File: Pagination.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
Pagination(Pageable pageable) {
    this.pageNumber = pageable.getPageNumber();
    this.pageSize = pageable.getPageSize();
    this.sort = new Sorting(pageable.getSort());
}
 
Example 16
Source File: JpaSoftwareModuleManagement.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Slice<AssignedSoftwareModule> findAllOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(
        final Pageable pageable, final long orderByDistributionId, final String searchText, final Long typeId) {

    final List<AssignedSoftwareModule> resultList = new ArrayList<>();
    final int pageSize = pageable.getPageSize();
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    // get the assigned software modules
    final CriteriaQuery<JpaSoftwareModule> assignedQuery = cb.createQuery(JpaSoftwareModule.class);
    final Root<JpaSoftwareModule> assignedRoot = assignedQuery.from(JpaSoftwareModule.class);
    assignedQuery.distinct(true);
    final ListJoin<JpaSoftwareModule, JpaDistributionSet> assignedDsJoin = assignedRoot
            .join(JpaSoftwareModule_.assignedTo);
    // build the specifications and then to predicates necessary by the
    // given filters
    final Predicate[] specPredicate = specificationsToPredicate(buildSpecificationList(searchText, typeId),
            assignedRoot, assignedQuery, cb,
            cb.equal(assignedDsJoin.get(JpaDistributionSet_.id), orderByDistributionId));
    // if we have some predicates then add it to the where clause of the
    // multi select
    assignedQuery.where(specPredicate);
    assignedQuery.orderBy(cb.asc(assignedRoot.get(JpaSoftwareModule_.name)),
            cb.asc(assignedRoot.get(JpaSoftwareModule_.version)));
    // don't page the assigned query on database, we need all assigned
    // software modules to filter
    // them out in the unassigned query
    final List<JpaSoftwareModule> assignedSoftwareModules = entityManager.createQuery(assignedQuery)
            .getResultList();
    // map result
    if (pageable.getOffset() < assignedSoftwareModules.size()) {
        assignedSoftwareModules
                .subList((int) pageable.getOffset(),
                        Math.min(assignedSoftwareModules.size(), pageable.getPageSize()))
                .forEach(sw -> resultList.add(new AssignedSoftwareModule(sw, true)));
    }

    if (assignedSoftwareModules.size() >= pageSize) {
        return new SliceImpl<>(resultList);
    }

    // get the unassigned software modules
    final CriteriaQuery<JpaSoftwareModule> unassignedQuery = cb.createQuery(JpaSoftwareModule.class);
    unassignedQuery.distinct(true);
    final Root<JpaSoftwareModule> unassignedRoot = unassignedQuery.from(JpaSoftwareModule.class);

    Predicate[] unassignedSpec;
    if (!assignedSoftwareModules.isEmpty()) {
        unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot,
                unassignedQuery, cb, cb.not(unassignedRoot.get(JpaSoftwareModule_.id).in(
                        assignedSoftwareModules.stream().map(SoftwareModule::getId).collect(Collectors.toList()))));
    } else {
        unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot,
                unassignedQuery, cb);
    }

    unassignedQuery.where(unassignedSpec);
    unassignedQuery.orderBy(cb.asc(unassignedRoot.get(JpaSoftwareModule_.name)),
            cb.asc(unassignedRoot.get(JpaSoftwareModule_.version)));
    final List<JpaSoftwareModule> unassignedSoftwareModules = entityManager.createQuery(unassignedQuery)
            .setFirstResult((int) Math.max(0, pageable.getOffset() - assignedSoftwareModules.size()))
            .setMaxResults(pageSize).getResultList();
    // map result
    unassignedSoftwareModules.forEach(sw -> resultList.add(new AssignedSoftwareModule(sw, false)));

    return new SliceImpl<>(resultList);
}
 
Example 17
Source File: SimpleTaskExplorerTests.java    From spring-cloud-task with Apache License 2.0 4 votes vote down vote up
private void verifyPageResults(Pageable pageable, int totalNumberOfExecs) {
	Map<Long, TaskExecution> expectedResults = createSampleDataSet(
			totalNumberOfExecs);
	List<Long> sortedExecIds = getSortedOfTaskExecIds(expectedResults);
	Iterator<Long> expectedTaskExecutionIter = sortedExecIds.iterator();
	// Verify pageable totals
	Page<TaskExecution> taskPage = this.taskExplorer.findAll(pageable);
	int pagesExpected = (int) Math
			.ceil(totalNumberOfExecs / ((double) pageable.getPageSize()));
	assertThat(taskPage.getTotalPages())
			.as("actual page count return was not the expected total")
			.isEqualTo(pagesExpected);
	assertThat(taskPage.getTotalElements())
			.as("actual element count was not the expected count")
			.isEqualTo(totalNumberOfExecs);

	// Verify pagination
	Pageable actualPageable = PageRequest.of(0, pageable.getPageSize());
	boolean hasMorePages = taskPage.hasContent();
	int pageNumber = 0;
	int elementCount = 0;
	while (hasMorePages) {
		taskPage = this.taskExplorer.findAll(actualPageable);
		hasMorePages = taskPage.hasNext();
		List<TaskExecution> actualTaskExecutions = taskPage.getContent();
		int expectedPageSize = pageable.getPageSize();
		if (!hasMorePages && pageable.getPageSize() != actualTaskExecutions.size()) {
			expectedPageSize = totalNumberOfExecs % pageable.getPageSize();
		}
		assertThat(actualTaskExecutions.size()).as(String.format(
				"Element count on page did not match on the %n page", pageNumber))
				.isEqualTo(expectedPageSize);
		for (TaskExecution actualExecution : actualTaskExecutions) {
			assertThat(actualExecution.getExecutionId())
					.as(String.format("Element on page %n did not match expected",
							pageNumber))
					.isEqualTo((long) expectedTaskExecutionIter.next());
			TestVerifierUtils.verifyTaskExecution(
					expectedResults.get(actualExecution.getExecutionId()),
					actualExecution);
			elementCount++;
		}
		actualPageable = taskPage.nextPageable();
		pageNumber++;
	}
	// Verify actual totals
	assertThat(pageNumber).as("Pages processed did not equal expected")
			.isEqualTo(pagesExpected);
	assertThat(elementCount).as("Elements processed did not equal expected,")
			.isEqualTo(totalNumberOfExecs);
}
 
Example 18
Source File: QueryDslRepositorySupportExt.java    From springlets with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the given {@link Pageable} to the given {@link JPQLQuery}.
 * Allows to map the attributes to order as provided in the {@link Pageable}
 * to real entity attributes. This might be used to work with projections
 * or DTOs whose attributes don't have the same name as the entity ones.
 *
 * It allows to map to more than one entity attribute. As an example, if
 * the DTO used to create the {@link Pageable} has a fullName attribute, you
 * could map that attribute to two entity attributes: name and surname.
 * In this case, the {@link Pageable} defines an order by a fullName
 * attribute, but que query will order by name and surname instead.
 *
 * @param pageable the ordering and paging
 * @param query
 * @param attributeMapping definition of a mapping of order attribute names
 *        to real entity ones
 * @return the updated query
 */
protected JPQLQuery<T> applyPagination(Pageable pageable, JPQLQuery<T> query,
    Map<String, Path<?>[]> attributeMapping) {

  if (pageable == null) {
    return query;
  }

  Pageable mappedPageable;
  Sort sort = pageable.getSort();
  if (sort != null) {
    List<Sort.Order> mappedOrders = new ArrayList<Sort.Order>();
    for (Sort.Order order : sort) {
      if (!attributeMapping.containsKey(order.getProperty())) {
        LOG.warn(
            "The property (%1) is not included in the attributeMapping, will order "
                + "using the property as it is",
            order.getProperty());
        mappedOrders.add(order);
      } else {
        Path<?>[] paths = attributeMapping.get(order.getProperty());
        for (Path<?> path : paths) {
          Sort.Order mappedOrder =
              new Sort.Order(order.getDirection(), preparePropertyPath(path));
          mappedOrders.add(mappedOrder);
        }
      }
    }
    if (mappedOrders.isEmpty()) {
      // No properties to order by are available, so don't apply ordering and return the query
      // as it is
      return query;
    }
    mappedPageable =
        new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(mappedOrders));
    return applyPagination(mappedPageable, query);
  } else {
    return applyPagination(pageable, query);
  }

}
 
Example 19
Source File: CypherAdapterUtils.java    From sdn-rx with Apache License 2.0 3 votes vote down vote up
public static StatementBuilder.BuildableStatement addPagingParameter(
	NodeDescription<?> nodeDescription,
	Pageable pageable,
	StatementBuilder.OngoingReadingAndReturn returning) {

	Sort sort = pageable.getSort();

	long skip = pageable.getOffset();

	int pageSize = pageable.getPageSize();

	return returning.orderBy(toSortItems(nodeDescription, sort)).skip(skip).limit(pageSize);
}
 
Example 20
Source File: BookController.java    From Spring with Apache License 2.0 3 votes vote down vote up
/**
 *  Pageable и Sort передается в аргументе метода благодаря:
 *
 *  <mvc:annotation-driven conversion-service="conversionService">
 *         <mvc:argument-resolvers>
 *
 *             <bean class="org.springframework.data.web.PageableHandlerMethodArgumentResolver">
 *                 <property name="maxPageSize" value="3"/>
 *             </bean>

 *             <bean class="org.springframework.data.web.SortHandlerMethodArgumentResolver"/>
 *         </mvc:argument-resolvers>
 *     </mvc:annotation-driven>
 */
@RequestMapping("/books")
public String showBooksPageable(Model model, Pageable pageable, Sort sort) {
    final PageRequest pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
    final Page<Book> books = repository.findAll(pageRequest);
    model.addAttribute("page", books);
    model.addAttribute("sort", (sort != null) ? sort.iterator().next().getProperty(): "");
    return "books";
}