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

The following examples show how to use org.springframework.data.domain.Pageable#getSort() . 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: LinqImpl.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
@Override
public <T> List<T> list(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.list(pageable);
	}
	if (pageable == null) {
		return list();
	} else {
		Sort sort = pageable.getSort();
		orders.addAll(QueryUtils.toOrders(sort, root, cb));
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		return transform(query, false);
	}
}
 
Example 2
Source File: CustomSearchRepositoryImpl.java    From klask-io with GNU General Public License v3.0 6 votes vote down vote up
/**
 * add the sort order to the request searchRequestBuilder
 * if the frontend send sort with "path : desc". It should be converted to "path.raw" : {"order" : "desc" }
 * https://www.elastic.co/guide/en/elasticsearch/guide/current/multi-fields.html#multi-fields
 *
 * @param pageable
 * @param searchRequestBuilder
 */
private void addPagingAndSortingToSearchRequest(Pageable pageable, SearchRequestBuilder searchRequestBuilder) {
    //par défaut, renvoi la première page trié sur le _score ou le _doc, si rien n'est spécifié
    //effectue le tri
    if (pageable != null) {

        searchRequestBuilder
            .setFrom(pageable.getOffset())
            .setSize(pageable.getPageSize());

        if (pageable.getSort() != null) {
            pageable.getSort().forEach(
                order -> searchRequestBuilder.addSort(
                    Constants.ORDER_FIELD_MAPPING.get(order.getProperty()),
                    SortOrder.valueOf(order.getDirection().name()))
            );
        }
    }
}
 
Example 3
Source File: AqlUtils.java    From spring-data with Apache License 2.0 6 votes vote down vote up
private static StringBuilder buildPageableClause(
	final Pageable pageable,
	@Nullable final String varName,
	final StringBuilder clause) {

	if (pageable.isUnpaged()) {
		return clause;
	}

	final Sort sort = pageable.getSort();
	buildSortClause(sort, varName, clause);

	if (sort.isSorted()) {
		clause.append(' ');
	}

	clause.append("LIMIT ").append(pageable.getOffset()).append(", ").append(pageable.getPageSize());
	return clause;
}
 
Example 4
Source File: SolrPageRequest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object obj) {

	if (this == obj) {
		return true;
	}
	if (obj == null || !(obj instanceof Pageable)) {
		return false;
	}

	Pageable other = (Pageable) obj;
	if (page != other.getPageNumber()) {
		return false;
	}
	if (size != other.getPageSize()) {
		return false;
	}
	if (sort == null) {
		if (other.getSort() != null) {
			return false;
		}
	} else if (!sort.equals(other.getSort())) {
		return false;
	}
	return true;
}
 
Example 5
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 6
Source File: JpaUtil.java    From linq with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
/**
 * 分页条件查询
 * @param cq 条件
 * @param pageable 分页信息
 * @param <T> 领域类(实体类)范型
 * @return 分页结果
 */
public static <T> Page<T> findAll(CriteriaQuery<T> cq, Pageable pageable) {
	Class<T> domainClass = cq.getResultType();
	Root<T> root;
	if (CollectionUtils.isEmpty(cq.getRoots())) {
		root = cq.from(domainClass);
	} else {
		root = (Root<T>) cq.getRoots().iterator().next();
	}
	EntityManager em = getEntityManager(domainClass);
	if (pageable == null) {
		List<T> list = findAll(cq);
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		cq.orderBy(QueryUtils.toOrders(sort, root, em.getCriteriaBuilder()));
		TypedQuery<T> query = em.createQuery(cq);
		
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		Long total = count(cq);
		List<T> content = total > pageable.getOffset() ? query.getResultList() : Collections.<T> emptyList();

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 7
Source File: LinqImpl.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
public <T> org.springframework.data.domain.Page<T> paging(Pageable pageable) {
	if (parent != null) {
		beforeExecute(sq);
		return parent.paging(pageable);
	}
	List<T> list;
	if (pageable == null) {
		list = list();
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		orders.addAll(QueryUtils.toOrders(sort, root, cb));
		beforeExecute(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		Long total = JpaUtil.count(criteria);
		List<T> content = Collections.<T> emptyList();
		if (total > pageable.getOffset()) {
			content = transform(query, false);
		}

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 8
Source File: JdbcTaskExecutionDao.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
private Page<TaskExecution> queryForPageableResults(Pageable pageable,
		String selectClause, String fromClause, String whereClause,
		MapSqlParameterSource queryParameters, long totalCount) {
	SqlPagingQueryProviderFactoryBean factoryBean = new SqlPagingQueryProviderFactoryBean();
	factoryBean.setSelectClause(selectClause);
	factoryBean.setFromClause(fromClause);
	if (StringUtils.hasText(whereClause)) {
		factoryBean.setWhereClause(whereClause);
	}
	final Sort sort = pageable.getSort();
	final LinkedHashMap<String, Order> sortOrderMap = new LinkedHashMap<>();

	if (sort != null) {
		for (Sort.Order sortOrder : sort) {
			sortOrderMap.put(sortOrder.getProperty(),
					sortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING);
		}
	}

	if (!CollectionUtils.isEmpty(sortOrderMap)) {
		factoryBean.setSortKeys(sortOrderMap);
	}
	else {
		factoryBean.setSortKeys(this.orderMap);
	}

	factoryBean.setDataSource(this.dataSource);
	PagingQueryProvider pagingQueryProvider;
	try {
		pagingQueryProvider = factoryBean.getObject();
		pagingQueryProvider.init(this.dataSource);
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
	String query = pagingQueryProvider.getPageQuery(pageable);
	List<TaskExecution> resultList = this.jdbcTemplate.query(getQuery(query),
			queryParameters, new TaskExecutionRowMapper());
	return new PageImpl<>(resultList, pageable, totalCount);
}
 
Example 9
Source File: FileResource.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
/**
 * GET  /files : get all the files.
 *
 * @param pageable the pagination information
 * @param version the version filter if set
 * @param project the project filter if set
 * @return the ResponseEntity with status 200 (OK) and the list of files in body
 * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
 */
@RequestMapping(value = "/files",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<File>> getAllFiles(@RequestParam(required = false) List<String> version,
                                              @RequestParam(required = false) List<String> project,
                                              @RequestParam(required = false) List<String> extension,
                                              Pageable pageable)
    throws URISyntaxException {
    //check if pageable is ok (has sort, page number, page size) and set to default if necessary
    pageable = CheckOrUpdatePageable(pageable);
    log.debug("REST request to get page {} for All Files with filter version {} and project {}", pageable.getPageNumber() + 1, version, project);

    //verification if we got a request with a big page number wich is greater than the max result search window
    if (pageable.getPageNumber() * pageable.getPageSize() >= Constants.MAX_RESULT_SEARCH_WINDOW) {
        log.warn("getAllFiles : page request too high : {}", pageable.getPageNumber());
        pageable = new PageRequest(0, pageable.getPageSize(), pageable.getSort());
    }
    Page<File> page;
    if (extension != null && extension.contains("empty")) {
        extension.add("");
        extension.remove("empty");
    }

    //page = fileSearchRepository.findAll(pageable);
    page = customSearchRepository.customfindAll(pageable, version, project, extension);
    //page = customSearchRepository.findWithHighlightedSummary(pageable,"",version);
    //Page<File> page = customSearchRepository.findWithHighlightedSummary("", pageable);


    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/files");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 10
Source File: IgniteQueryGenerator.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Add a dynamic part of a query for the pagination support.
 *
 * @param sql Builder instance.
 * @param pageable Pageable instance.
 * @return Builder instance.
 */
public static StringBuilder addPaging(StringBuilder sql, Pageable pageable) {
    if (pageable.getSort() != null)
        addSorting(sql, pageable.getSort());

    sql.append(" LIMIT ").append(pageable.getPageSize()).append(" OFFSET ").append(pageable.getOffset());

    return sql;
}
 
Example 11
Source File: QueryBuilder.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public QueryBuilder with(Pageable pageable) {
	Sort sort = pageable.getSort();
	if(sort != null) {
		with(sort);
	}

	if(pageable.getPageSize() > 0) {
		withLimit(pageable.getPageSize());
	}

	return this;
}
 
Example 12
Source File: LinqImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Page<T> paging(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.paging(pageable);
	}
	List<T> list;
	if (pageable == null) {
		list = list();
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		if (sort != null) {
			orders.addAll(QueryUtils.toOrders(sort, root, cb));
		}
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		Long total = JpaUtil.count(criteria);
		List<T> content = Collections.<T> emptyList();
		if (total > pageable.getOffset()) {
			content = transform(query, false);
		}

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 13
Source File: SimpleDynamoDBPagingAndSortingRepository.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@Override
public Page<T> findAll(Pageable pageable) {

	if (pageable.getSort() != null) {
		throw new UnsupportedOperationException("Sorting not supported for find all scan operations");
	}

	DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
	// Scan to the end of the page after the requested page
	int scanTo = pageable.getOffset() + (2 * pageable.getPageSize());
	scanExpression.setLimit(scanTo);
	PaginatedScanList<T> paginatedScanList = dynamoDBOperations.scan(domainType, scanExpression);
	Iterator<T> iterator = paginatedScanList.iterator();
	int processedCount = 0;
	if (pageable.getOffset() > 0) {
		processedCount = scanThroughResults(iterator, pageable.getOffset());
		if (processedCount < pageable.getOffset())
			return new PageImpl<T>(new ArrayList<T>());
	}
	// Scan ahead to retrieve the next page count
	List<T> results = readPageOfResults(iterator, pageable.getPageSize());
	
	assertScanEnabled(enableScanPermissions.isFindAllPaginatedScanEnabled(), "findAll(Pageable pageable)");
	assertScanCountEnabled(enableScanPermissions.isFindAllUnpaginatedScanCountEnabled(), "findAll(Pageable pageable)");

	int totalCount = dynamoDBOperations.count(domainType, scanExpression);
	
	return new PageImpl<T>(results, pageable, totalCount);

}
 
Example 14
Source File: SqlSessionRepositorySupport.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
protected <X, Y> Page<X> findByPager(Pageable pager, String selectStatement,
		String countStatement, Y condition, Map<String, Object> otherParams) {
	Map<String, Object> params = new HashMap<>();
	params.put("__offset", pager.getOffset());
	params.put("__pageSize", pager.getPageSize());
	params.put("__offsetEnd", pager.getOffset() + pager.getPageSize());
	if (condition instanceof Sort && ((Sort) condition).isSorted()) {
		params.put("__sort", condition);
	}
	else if (null != pager && null != pager.getSort() && pager.getSort().isSorted()) {
		params.put("__sort", pager.getSort());
	}
	params.put("__condition", condition);

	if (!CollectionUtils.isEmpty(otherParams)) {
		params.putAll(otherParams);
	}
	List<X> result = selectList(selectStatement, params);

	long total = calculateTotal(pager, result);
	if (total < 0) {
		total = selectOne(countStatement, params);
	}

	return new PageImpl<>(result, pager, total);
}
 
Example 15
Source File: BaseServiceImpl.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
protected void getPage(Pageable pageable) {
    String order=null;
    if(pageable.getSort()!=null){
        order= pageable.getSort().toString();
        order=order.replace(":","");
        if("UNSORTED".equals(order)){
            order="id desc";
        }
    }
    PageHelper.startPage(pageable.getPageNumber()+1, pageable.getPageSize(),order);
}
 
Example 16
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 17
Source File: FindPageSpecificationInterceptor.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    final Object[] parameterValues = context.getParameterValues();
    if (parameterValues.length != 2) {
        throw new IllegalStateException("Expected exactly 2 arguments to method");
    }
    final Object parameterValue = parameterValues[0];
    final Object pageableObject = parameterValues[1];
    if (parameterValue instanceof Specification) {
        Specification specification = (Specification) parameterValue;
        final EntityManager entityManager = jpaOperations.getCurrentEntityManager();
        final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<Object> query = criteriaBuilder.createQuery((Class<Object>) getRequiredRootEntity(context));
        final Root<Object> root = query.from((Class<Object>) getRequiredRootEntity(context));
        final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder);
        query.where(predicate);
        query.select(root);

        if (pageableObject instanceof Pageable) {
            Pageable pageable = (Pageable) pageableObject;
            final Sort sort = pageable.getSort();
            if (sort.isSorted()) {
                final List<Order> orders = QueryUtils.toOrders(sort, root, criteriaBuilder);
                query.orderBy(orders);
            }
            final TypedQuery<Object> typedQuery = entityManager
                    .createQuery(query);
            if (pageable.isUnpaged()) {
                return new PageImpl<>(
                    typedQuery
                            .getResultList()
                );
            } else {
                typedQuery.setFirstResult((int) pageable.getOffset());
                typedQuery.setMaxResults(pageable.getPageSize());
                final List<Object> results = typedQuery.getResultList();
                final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
                final Root<?> countRoot = countQuery.from(getRequiredRootEntity(context));
                final Predicate countPredicate = specification.toPredicate(root, query, criteriaBuilder);
                countQuery.where(countPredicate);
                countQuery.select(criteriaBuilder.count(countRoot));

                return new PageImpl<>(
                        results,
                        pageable,
                        entityManager.createQuery(countQuery).getSingleResult()
                );
            }

        } else {
            return new PageImpl<>(
                    entityManager
                            .createQuery(query)
                            .getResultList()
            );
        }
    } else {
        throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class);
    }
}
 
Example 18
Source File: CodelessDaoProxy.java    From sca-best-practice with Apache License 2.0 4 votes vote down vote up
protected <T> TypedQuery<T> getQuery(Class<T> clazz, @Nullable Specification<T> spec, Pageable pageable) {

        Sort sort = pageable.isPaged() ? pageable.getSort() : Sort.unsorted();
        return getQuery(clazz, spec, sort);
    }
 
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: SimpleBaseRepository.java    From es with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link javax.persistence.TypedQuery} from the given {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return
 */
private TypedQuery<M> getQuery(Specification<M> spec, Pageable pageable) {

    Sort sort = pageable == null ? null : pageable.getSort();
    return getQuery(spec, sort);
}