Java Code Examples for org.springframework.data.domain.Sort#Order

The following examples show how to use org.springframework.data.domain.Sort#Order . 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: ArangoRepositoryTest.java    From spring-data with Apache License 2.0 7 votes vote down vote up
@Test
public void findAllSortByExampleTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	toBeRetrieved.add(new Customer("A", "Z", 0));
	toBeRetrieved.add(new Customer("B", "C", 0));
	toBeRetrieved.add(new Customer("B", "D", 0));
	repository.saveAll(toBeRetrieved);
	repository.save(new Customer("A", "A", 1));
	final Example<Customer> example = Example.of(new Customer("", "", 0),
		ExampleMatcher.matchingAny().withIgnoreNullValues().withIgnorePaths(new String[] { "location", "alive" }));
	final List<Sort.Order> orders = new LinkedList<>();
	orders.add(new Sort.Order(Sort.Direction.ASC, "name"));
	orders.add(new Sort.Order(Sort.Direction.ASC, "surname"));
	final Sort sort = Sort.by(orders);
	final Iterable<Customer> retrieved = repository.findAll(example, sort);
	assertTrue(equals(toBeRetrieved, retrieved, cmp, eq, true));
}
 
Example 2
Source File: DefaultNotificationManager.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
public PageRequest getPageRequestForNotifications(Integer pageNumber, Integer pageSize, String sortField, String sortOrder) {
    Integer page = ObjectUtils.defaultIfNull(pageNumber, 0);
    Integer size = ObjectUtils.defaultIfNull(pageSize, Integer.MAX_VALUE);
    boolean sortQuery = false;
    String sortingField = "createdAt";
    // We can only modify the query for the fields that exist in NotificationContent
    if (StringUtils.isNotBlank(sortField) && "createdAt".equalsIgnoreCase(sortField)
            || "provider".equalsIgnoreCase(sortField)
            || "providerCreationTime".equalsIgnoreCase(sortField)
            || "notificationType".equalsIgnoreCase(sortField)
            || "content".equalsIgnoreCase(sortField)) {
        sortingField = sortField;
        sortQuery = true;
    }
    Sort.Order sortingOrder = Sort.Order.desc(sortingField);
    if (StringUtils.isNotBlank(sortOrder) && sortQuery && Sort.Direction.ASC.name().equalsIgnoreCase(sortOrder)) {
        sortingOrder = Sort.Order.asc(sortingField);
    }
    return PageRequest.of(page, size, Sort.by(sortingOrder));
}
 
Example 3
Source File: MessageServiceImpl.java    From distributed-transaction-process with MIT License 6 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
@Override
public void reSendAllDeadByQueueName(String queueName, int batchSize)
        throws CheckException, ServiceException {

    int pageNum = 0;
    int totalPage = 1;
    while (pageNum++ < totalPage) {
        Sort.Order order = new Sort.Order("createTime");
        Sort sort = new Sort(order);
        Pageable pageable = new PageRequest(pageNum, batchSize, sort);
        Page<Message> page = messageRepository.findByConsumerQueueAndDead(queueName, Boolean.TRUE, pageable);

        totalPage = page.getTotalPages();
        reSendNoDead(page.getContent());
    }
}
 
Example 4
Source File: DictServiceImpl.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@Override
@Cacheable(key = "'page_dict_' + #p0.currentPage + '_' + #p0.pageSize + '_' + #p1.type + '_' + #p1.label")
public PageBean<Dict> findAll(PageParams pageParams, Dict dict) {
	QDict qDict = QDict.dict;
	// 用户名查询条件
	Predicate qLabelPredicate = null;
	Predicate qTypePredicate = null;
	if (null != dict) {
		if (StringHelper.isNotBlank(dict.getLabel())) {
			qLabelPredicate = qDict.label.like("%" + dict.getLabel().trim() + "%");
		}
		if (StringHelper.isNotBlank(dict.getType())) {
			qTypePredicate = qDict.type.like("%" + dict.getType().trim() + "%");
		}
	}

	Predicate predicate = qDict.id.goe(0).and(qTypePredicate).and(qLabelPredicate);

	Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "id"));
	PageRequest pageRequest = PageUtils.of(pageParams, sort);
	Page<Dict> pageList = dictRepository.findAll(predicate, pageRequest);
	return PageUtils.of(pageList);
}
 
Example 5
Source File: SortJsonComponent.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Override
public Sort deserialize(JsonParser jsonParser,
		DeserializationContext deserializationContext) throws IOException {
	TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
	if (treeNode.isArray()) {
		ArrayNode arrayNode = (ArrayNode) treeNode;
		List<Sort.Order> orders = new ArrayList<>();
		for (JsonNode jsonNode : arrayNode) {
			Sort.Order order = new Sort.Order(
					Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
					jsonNode.get("property").textValue());
			orders.add(order);
		}
		return Sort.by(orders);
	}
	return null;
}
 
Example 6
Source File: MarketService.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public List<KLine> findAllKLine(String symbol,long fromTime,long toTime,String period){
    Criteria criteria = Criteria.where("time").gte(fromTime).andOperator(Criteria.where("time").lte(toTime));
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"time"));
    Query query = new Query(criteria).with(sort);
    List<KLine> kLines = mongoTemplate.find(query,KLine.class,"exchange_kline_"+symbol+"_"+ period);
    return kLines;
}
 
Example 7
Source File: PaginationInterceptor.java    From platform with Apache License 2.0 5 votes vote down vote up
private static List<OrderByElement> addOrderByElements(List<Sort.Order> orderList,
                                                       List<OrderByElement> orderByElements) {
    orderByElements = CollectionUtils.isEmpty(orderByElements) ? new ArrayList<>(orderList.size()) : orderByElements;
    List<OrderByElement> orderByElementList = orderList.stream().map(item -> {
        OrderByElement element = new OrderByElement();
        element.setExpression(new Column(item.getProperty()));
        element.setAsc(item.getDirection().isAscending());
        return element;
    }).collect(Collectors.toList());
    orderByElements.addAll(orderByElementList);
    return orderByElements;
}
 
Example 8
Source File: Criteria.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 排序
 * QueryBuilderUtils.sort("name","id.desc");表示先以name升序,之后以xh降序
 */
public  Sort sort(String... fields) {
    List<Sort.Order> orders = new ArrayList<Sort.Order>();
    for(String f:fields) {
        orders.add(generateOrderStatic(f));
    }
    return new Sort(orders);
}
 
Example 9
Source File: LogServiceImpl.java    From SuperBoot with MIT License 5 votes vote down vote up
@Override
public BaseResponse getRequestCountByWeek() throws BaseException {

    //查询条件信息
    Criteria operator = new Criteria();
    operator.andOperator(
            //查询小于等于今天
            Criteria.where("execDate").lte(DateUtil.today()),
            //查询大于等于7天前
            Criteria.where("execDate").gte(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -7)))

    );

    //查询条件
    MatchOperation matchOperation = Aggregation.match(operator);


    //分组信息及返回count列命名
    GroupOperation groupOperation = Aggregation.group("appName", "execDate").count().as("count");

    //排序信息
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, "execDate"));
    SortOperation sortOperation = Aggregation.sort(sort);

    //组合条件
    Aggregation aggregation = Aggregation.newAggregation(DataInfo.class, matchOperation, groupOperation, sortOperation);

    // 执行操作
    AggregationResults<Map> aggregationResults = template.aggregate(aggregation, DataInfo.class, Map.class);

    return new BaseResponse(aggregationResults.getMappedResults());
}
 
Example 10
Source File: BaseServiceLogRequestQueryConverter.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Sort sort(BaseServiceLogRequest request) {
  String sortBy = request.getSortBy();
  String sortType = request.getSortType();
  Sort.Order defaultSortOrder;
  if (StringUtils.isNotBlank(sortBy)) {
    Sort.Direction direction = StringUtils.equals(sortType, LogSearchConstants.ASCENDING_ORDER) ? Sort.Direction.ASC : Sort.Direction.DESC;
    defaultSortOrder = new Sort.Order(direction, sortBy);
  } else {
    defaultSortOrder = new Sort.Order(Sort.Direction.DESC, LOGTIME);
  }
  Sort.Order sequenceIdOrder = new Sort.Order(Sort.Direction.DESC, SEQUENCE_ID);
  return new Sort(defaultSortOrder, sequenceIdOrder);
}
 
Example 11
Source File: MarketService.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 查找某时间段内的交易量
 * @param symbol
 * @param timeStart
 * @param timeEnd
 * @return
 */
public BigDecimal findTradeVolume(String symbol, long timeStart, long timeEnd){
    Criteria criteria = Criteria.where("time").gt(timeStart)
            .andOperator(Criteria.where("time").lte(timeEnd));
            //.andOperator(Criteria.where("volume").gt(0));
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"time"));
    Query query = new Query(criteria).with(sort);
    List<KLine> kLines =  mongoTemplate.find(query,KLine.class,"exchange_kline_"+symbol+"_1min");
    BigDecimal totalVolume = BigDecimal.ZERO;
    for(KLine kLine:kLines){
        totalVolume = totalVolume.add(kLine.getVolume());
    }
    return totalVolume;
}
 
Example 12
Source File: PageableAssert.java    From code-examples with MIT License 5 votes vote down vote up
PageableAssert hasSort(String field, Sort.Direction direction) {

		Sort.Order actualOrder = actual.getSort().getOrderFor(field);

		if (actualOrder == null) {
			failWithMessage("expected sort for field <%s> to be <%s> but was null", field, direction);
		} else if (actualOrder.getDirection() != direction) {
			failWithMessage("expected sort for field <%s> to be <%s> but was <%s>", field, direction, actualOrder.getDirection());
		}

		return this;
	}
 
Example 13
Source File: ExchangeCoinService.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public List<ExchangeCoin> findAllEnabled() {
    Specification<ExchangeCoin> spec = (root, criteriaQuery, criteriaBuilder) -> {
        Path<String> enable = root.get("enable");
        criteriaQuery.where(criteriaBuilder.equal(enable, 1));
        return null;
    };
    Sort.Order order = new Sort.Order(Sort.Direction.ASC, "sort");
    Sort sort = new Sort(order);
    return coinRepository.findAll(spec, sort);
}
 
Example 14
Source File: ExchangeOrderService.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * Api 查询订单接口
 *
 * @param memberId
 * @param symbol
 * @param direction
 * @return
 */
public Page<ExchangeOrder> findCurrentTradingOrderForApi(long memberId, String symbol, ExchangeOrderDirection direction, int pageNo, int pageSize) {
    Sort orders = new Sort(new Sort.Order(Sort.Direction.DESC, "time"));
    PageRequest pageRequest = new PageRequest(pageNo, pageSize, orders);
    Criteria<ExchangeOrder> specification = new Criteria<ExchangeOrder>();
    specification.add(Restrictions.eq("symbol", symbol, false));
    specification.add(Restrictions.eq("memberId", memberId, false));
    specification.add(Restrictions.eq("status", ExchangeOrderStatus.TRADING, false));
    specification.add(Restrictions.eq("direction", direction, false));
    return exchangeOrderRepository.findAll(specification, pageRequest);
}
 
Example 15
Source File: SpringPageableRequestArgumentBinder.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public BindingResult<Pageable> bind(ArgumentConversionContext<Pageable> context, HttpRequest<?> source) {
    HttpParameters parameters = source.getParameters();
    int page = Math.max(parameters.getFirst(configuration.getPageParameterName(), Integer.class)
            .orElse(0), 0);
    final int configuredMaxSize = configuration.getMaxPageSize();
    final int defaultSize = configuration.getDefaultPageSize();
    int size = Math.min(parameters.getFirst(configuration.getSizeParameterName(), Integer.class)
            .orElse(defaultSize), configuredMaxSize);
    String sortParameterName = configuration.getSortParameterName();
    boolean hasSort = parameters.contains(sortParameterName);
    Pageable pageable;
    Sort sort;
    if (hasSort) {
        List<String> sortParams = parameters.getAll(sortParameterName);

        List<Sort.Order> orders = sortParams.stream()
                .map(sortMapper)
                .collect(Collectors.toList());
        sort = Sort.by(orders);
    } else {
        sort = Sort.unsorted();
    }

    if (size < 1) {
        if (page == 0 && configuredMaxSize < 1 && sort.isUnsorted()) {
            pageable = Pageable.unpaged();
        } else {
            pageable = PageRequest.of(page, defaultSize, sort);
        }
    } else {
        pageable = PageRequest.of(page, size, sort);
    }

    return () -> Optional.of(pageable);
}
 
Example 16
Source File: Criteria.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 排序
 * QueryBuilderUtils.sort("name","id.desc");表示先以name升序,之后以xh降序
 */
public  Sort sort(String... fields) {
    List<Sort.Order> orders = new ArrayList<Sort.Order>();
    for(String f:fields) {
        orders.add(generateOrderStatic(f));
    }
    return new Sort(orders);
}
 
Example 17
Source File: JpaUtils.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 根据 jqgrid 传过来的排序信息,构造排序所需要的 Sort
 *
 * @param order
 * @return
 */
private static Sort getJqGirdSort(Order order) {

    if (order.getProperty() == null || order.getProperty().isEmpty()) {
        log.info("排序字段为 null 或 空");
        return null;
    }

    //排序字段
    if (!order.getProperty().contains(",")) { //未分组

        return createSort(order.getDirection().toString(), order.getProperty());

    } else { //分组,grouping:true 时

        String[] arrays = StringUtils.removeEnd(order.getProperty().trim(), ",").split(",");  //传来的排序请求字符串,形如 sidx =name asc, herf desc,实际经过参数对应后变成字符串 name asc, herf desc,
        //arrays = {[name asc],[herf desc]}

        List<Sort.Order> orders = Lists.newArrayList();
        List<String> unique = Lists.newArrayList();   //为了避免同一个属性,重复添加。此情况发生在 grouping:true 时,没有进一步测试。
        for (String s : arrays) { //拼接所有的排序请求。
            String propertyT = StringUtils.substringBefore(s.trim(), " ");
            if (unique.contains(propertyT))
                continue;
            unique.add(propertyT);
            String directionT = StringUtils.substringAfter(s.trim(), " ");
            orders.add(createOrder(directionT, propertyT));
        }
        return createSort(orders);
    }
}
 
Example 18
Source File: MarketService.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
public ExchangeTrade findFirstTrade(String symbol,long fromTime,long toTime){
    Criteria criteria = Criteria.where("time").gte(fromTime).andOperator(Criteria.where("time").lte(toTime));
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"time"));
    Query query = new Query(criteria).with(sort);
    return mongoTemplate.findOne(query,ExchangeTrade.class,"exchange_trade_"+symbol);
}
 
Example 19
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 20
Source File: JpaUtils.java    From spring-boot with Apache License 2.0 2 votes vote down vote up
/**
 * 创建排序条件 Order
 *
 * @param direction
 * @param property
 * @return
 */
public static Sort.Order createOrder(String direction, String property) {
    Assert.isTrue(!property.isEmpty(), " 排序字段没有指定");
    return new Sort.Order(createDirection(direction), property);
}