當前位置: 首頁>>代碼示例>>Java>>正文


Java Sort類代碼示例

本文整理匯總了Java中org.springframework.data.domain.Sort的典型用法代碼示例。如果您正苦於以下問題:Java Sort類的具體用法?Java Sort怎麽用?Java Sort使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Sort類屬於org.springframework.data.domain包,在下文中一共展示了Sort類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getAppInfoByAppNames

import org.springframework.data.domain.Sort; //導入依賴的package包/類
@Override
public List<ApplicationDTO> getAppInfoByAppNames(List<String> names) {

    Aggregation aggregation = newAggregation(
        match(Criteria.where("appname").in(names).and("timestamp").exists(true)),
        sort(new Sort(DESC, "timestamp")),
        project("appname", "platform", "starrating",
                    "timestamp", "comment", "authorName","url"),
        group("appname", "platform")
            .push(new BasicDBObject("author", "$authorName")
                .append("rate", "$starrating" )
                .append("timestamp", "$timestamp")
                .append("comment", "$comment")
                .append("url", "$url")
            ).as("reviews"),
        project("appname", "platform")
            .and("reviews").slice(8, 0)
    );

    //Convert the aggregation result into a List
    AggregationResults<ApplicationDTO> groupResults
            = mongoTemplate.aggregate(aggregation, Review.class, ApplicationDTO.class);

    return groupResults.getMappedResults();
}
 
開發者ID:BBVA,項目名稱:mirrorgate,代碼行數:26,代碼來源:ReviewRepositoryImpl.java

示例2: testSelectSort

import org.springframework.data.domain.Sort; //導入依賴的package包/類
/**
 * 分詞 查詢 商品名稱 and 描述 價格排序
 */
@Test
public void testSelectSort() {
    //組裝查詢
    BoolQueryBuilder builder = boolQuery();
    builder.must(matchQuery("goodsName", "百事")).must(matchQuery("description", "百事"));

    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
    searchQuery.addSort(new Sort(Sort.Direction.DESC, new String[]{"price"}));

    Page<GoodsModel> page = elasticsearchTemplate.queryForPage(searchQuery, GoodsModel.class);
    System.out.println(page.getSize());

    List<GoodsModel> GoodsESDocs = page.getContent();

    System.out.println(JSON.toJSONString(GoodsESDocs));

    Assert.assertThat(page.getTotalElements(), is(2L));
}
 
開發者ID:aillamsun,項目名稱:spring-boot-elastcsearch-example,代碼行數:22,代碼來源:GoodsESTest.java

示例3: createPageRequest

import org.springframework.data.domain.Sort; //導入依賴的package包/類
/**
 * Create pageable request with default sort.
 *
 * @param page Page.
 * @param defaultSort Default sort object.
 * @param caseSensitiveSortProperties List of case sensitive properties or {@link #CASE_SENSITIVE_PROPERTIES} for
 *                                       all properties to be case sensitive.
 * @return Page object.
 */
public static PageRequest createPageRequest(Pageable page, Sort defaultSort,
											Collection<String> caseSensitiveSortProperties) {
	Sort sort = page.getSort();
	sort = sort == null ? defaultSort : sort.and(defaultSort);

	List<Sort.Order> ignoreCaseOrderList = Collections.emptyList();
	if (sort != null) {
		ignoreCaseOrderList = StreamUtils.createStreamFromIterator(sort.iterator())
				.map(order -> {
					if (caseSensitiveSortProperties == CASE_SENSITIVE_PROPERTIES ||
							caseSensitiveSortProperties.contains(order.getProperty())) {
						return order.ignoreCase();
					}
					return order;
				})
				.collect(Collectors.toList());
	}

	if (ignoreCaseOrderList.isEmpty()) {
		return new PageRequest(page.getPageNumber(), page.getPageSize());
	}
	return new PageRequest(page.getPageNumber(), page.getPageSize(), new Sort(ignoreCaseOrderList));
}
 
開發者ID:ATLANTBH,項目名稱:owl,代碼行數:33,代碼來源:ServicesUtils.java

示例4: applyOrder

import org.springframework.data.domain.Sort; //導入依賴的package包/類
private static String applyOrder(String sql, Sort sort) {
    StringBuilder builder = new StringBuilder(sql);

    if (sort != null) {
        builder.append(ORDER_BY_SQL);
        String sep = "";
        for (Sort.Order order : sort) {
            builder.append(sep)
                .append(order.getProperty())
                .append(" ")
                .append(order.getDirection());
            sep = ", ";
        }
    }

    return builder.toString();
}
 
開發者ID:xm-online,項目名稱:xm-commons,代碼行數:18,代碼來源:PermittedRepository.java

示例5: pageRequestProtoToPageRequest

import org.springframework.data.domain.Sort; //導入依賴的package包/類
public static org.springframework.data.domain.PageRequest pageRequestProtoToPageRequest(PageRequest pageRequestProto) {
    if (pageRequestProto == null) {
        return null;
    }
    int page = pageRequestProto.getPage();
    int pageSize = pageRequestProto.getSize();

    // Limit lower bound
    pageSize = pageSize < 1 ? DEFAULT_PAGE_REQUEST.getPageSize() : pageSize;
    // Limit upper bound
    pageSize = pageSize > DEFAULT_MAX_PAGE_SIZE ? DEFAULT_MAX_PAGE_SIZE : pageSize;

    List<Sort.Order> orders = pageRequestProto.getOrdersList().stream()
        .map( o -> new Sort.Order(Sort.Direction.fromString(o.getDirection().toString()), o.getProperty()))
        .collect(Collectors.toList());
    Sort sort = orders.isEmpty() ? null : new Sort(orders);

    return new org.springframework.data.domain.PageRequest(page, pageSize, sort);
}
 
開發者ID:cbornet,項目名稱:generator-jhipster-grpc,代碼行數:20,代碼來源:_ProtobufMappers.java

示例6: getSortedField

import org.springframework.data.domain.Sort; //導入依賴的package包/類
private SortField<?> getSortedField(final String sortFieldName, final Sort.Direction sortDirection){
    SortOrder sortOrder;
    if (sortDirection == Sort.Direction.ASC) {
        sortOrder = SortOrder.ASC;
    } else {
        sortOrder = SortOrder.DESC;
    }
    switch (sortFieldName){
        case "id":
            return TRANSFER_TIMING_FILE_TRANSITION_HISTORY_ID.sort(sortOrder);
        case "atableName":
            return ATABLE.NAME.sort(sortOrder);
        case "username":
            return USER.USERNAME.sort(sortOrder);
        case "blablabla......... etc":
            // Etc for others
            return null;
        default:
            throw new IllegalArgumentException("Well how should it be handled? And should be same for all app to be consistent");
    }
}
 
開發者ID:Blackdread,項目名稱:filter-sort-jooq-api,代碼行數:22,代碼來源:TransferTimingPageRepositoryImplPureJooq.java

示例7: readingsByNameAndDevice

import org.springframework.data.domain.Sort; //導入依賴的package包/類
/**
 * Return a list of readings that are associated to a ValueDescripter and Device by name.
 * LimitExceededException (HTTP 413) if the number of readings exceeds the current max limit.
 * ServiceException (HTTP 503) for unknown or unanticipated issues.
 * 
 * @param valueDescriptorName - name of the matching ValueDescriptor
 * @param device name - name or id of the matching device associated to the event/reading
 * @param limit - maximum number of readings to return (must not exceed max limit)
 * @return - list of readings matching on the value descriptor and device name
 * @throws ServiceException (HTTP 503) for unknown or unanticipated issues
 * @throws LimitExceededException (HTTP 413) if the number of readings exceeds the current max
 *         limit
 */
@RequestMapping(value = "/name/{name:.+}/device/{device:.+}/{limit}", method = RequestMethod.GET)
@Override
public List<Reading> readingsByNameAndDevice(@PathVariable String name,
    @PathVariable String device, @PathVariable int limit) {
  if (limit > maxLimit)
    throw new LimitExceededException(LIMIT_ON_READING);
  try {
    PageRequest request =
        new PageRequest(0, determineLimit(limit), new Sort(Sort.Direction.DESC, SORT_CREATED));
    return readingRepos.findByNameAndDevice(name, device, request).getContent();
  } catch (Exception e) {
    logger.error(ERR_GETTING + e.getMessage());
    throw new ServiceException(e);
  }
}
 
開發者ID:edgexfoundry,項目名稱:core-data,代碼行數:29,代碼來源:ReadingControllerImpl.java

示例8: listToegangLeveringsautorisatie

import org.springframework.data.domain.Sort; //導入依賴的package包/類
/**
 * Haal een lijst van items op.
 * @param id id van Leveringsautorisatie
 * @param parameters request parameters
 * @param pageable paginering
 * @return lijst van item (inclusief paginering en sortering)
 */
@RequestMapping(value = "/{id}/toegangbijhoudingsautorisaties", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public final Page<ToegangBijhoudingsautorisatie> listToegangLeveringsautorisatie(
        @PathVariable(value = "id") final String id,
        @RequestParam final Map<String, String> parameters,
        @PageableDefault(size = 10) @SortDefault(sort = {DATUM_INGANG, DATUM_EINDE}, direction = Sort.Direction.ASC) final Pageable pageable) {
    parameters.put(ToegangBijhoudingsautorisatieController.PARAMETER_FILTER_BIJHOUDINGSAUTORISATIE, id);
    return toegangBijhoudingsautorisatieController.list(parameters, pageable);
}
 
開發者ID:MinBZK,項目名稱:OperatieBRP,代碼行數:17,代碼來源:BijhoudingsautorisatieController.java

示例9: showUserMessages

import org.springframework.data.domain.Sort; //導入依賴的package包/類
@RequestMapping(value = "/me/messages", method = RequestMethod.GET)
public String showUserMessages(Model model, @RequestParam(defaultValue = "1") int page) {
    page = page > 1 ? page - 1 : 0;

    Long userId = userService.getCurrentUserId();

    Page<Message> messages = messageRepository.findUserMessages(
        userId,
        new PageRequest(page, PAGE_SIZE, Sort.Direction.DESC, "id"));

    model.addAttribute("page", page + 1);
    model.addAttribute("totalPages", messages.getTotalPages());
    model.addAttribute("messages", messages);

    messageService.emptyUserUnreadMessages(userId);

    return "messages/user_all";
}
 
開發者ID:ugouku,項目名稱:shoucang,代碼行數:19,代碼來源:MessageController.java

示例10: getReplyByPage

import org.springframework.data.domain.Sort; //導入依賴的package包/類
@Override
public Page<Reply> getReplyByPage(Integer postsId, int pageNo, int length) {
    Sort.Order order = new Sort.Order(Sort.Direction.ASC, "id");
    Sort sort = new Sort(order);
    PageRequest pageable = new PageRequest(pageNo, length, sort);

    Specification<Reply> specification = new Specification<Reply>() {

        @Override
        public Predicate toPredicate(Root<Reply> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
            Path<Integer> $posts = root.get("posts");
            Predicate predicate = criteriaBuilder.and(criteriaBuilder.equal($posts, postsId));
            return predicate;
        }
    };
    Page<Reply> page = repository.findAll(specification, pageable);
    return page;
}
 
開發者ID:ChinaLHR,項目名稱:JavaQuarkBBS,代碼行數:19,代碼來源:ReplyServiceImpl.java

示例11: setUp

import org.springframework.data.domain.Sort; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    accountCapabilities = generateAccountCapabilities();
    entityCapabilities = generateEntityCapabilities();

    List<Capability> combinedCapabilities = new ArrayList<>();
    combinedCapabilities.addAll(accountCapabilities);
    combinedCapabilities.addAll(entityCapabilities);

    when(capabilityRepository.findAll(any(Sort.class))).thenReturn(combinedCapabilities);
    when(capabilityRepository.findByNameIgnoreCase(eq("accountcap"))).thenReturn(accountCapabilities.get(0));
    when(capabilityRepository.findByNameIgnoreCase(eq("entitycap"))).thenReturn(entityCapabilities.get(0));
    when(entityService.entitySearchGlobal(eq(entity), eq("ghan"))).thenReturn(Optional.empty());
    when(entityService.entitySearchGlobal(eq(entity), eq("bnarg"))).thenReturn(Optional.of(target));
    when(target.getCapabilities()).thenReturn(entityCapabilities);
    when(target.getAccount()).thenReturn(account);
    when(account.getCapabilities()).thenReturn(accountCapabilities);

    command = new CapabilityEditCommand(
            capabilityRepository,
            accountRepository,
            entityRepository,
            entityService);
}
 
開發者ID:scionaltera,項目名稱:emergentmud,代碼行數:27,代碼來源:CapabilityEditCommandTest.java

示例12: getPostAfterDate

import org.springframework.data.domain.Sort; //導入依賴的package包/類
/**
 * Handles a GET request by returning a collection of Post after a certain date.
 *
 * @param date             The date after which posts should be retrieved.
 * @param ordered          Whether the list should be ordered by latest or not.
 * @param sourcesWhitelist optional list of requested sources
 * @return The Posts in JSON.
 */
@ApiOperation("Get posts after a given date")
@RequestMapping(value = "/afterdate/{date}", method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
public Iterable<Post> getPostAfterDate(
    @PathVariable("date") long date,
    @RequestParam(required = false, defaultValue = "true", value = "ordered") boolean ordered,
    @PathVariable(required = false) String[] sourcesWhitelist) {

    BooleanExpression predicate = null;
    if (sourcesWhitelist != null) {
        predicate = notHidden()
            .and(QPost.post.publishedAt.after(new DateTime(date)))
            .and(isAllowed(sourcesWhitelist));
    } else {
        predicate = notHidden()
            .and(QPost.post.publishedAt.after(new DateTime(date)));
    }
    Sort sort = new Sort(Sort.Direction.DESC, "publishedAt");

    if (ordered) {
        return postRepository.findAll(predicate, sort);
    } else {
        return postRepository.findAll(predicate);
    }
}
 
開發者ID:BakkerTom,項目名稱:happy-news,代碼行數:34,代碼來源:PostController.java

示例13: sorting

import org.springframework.data.domain.Sort; //導入依賴的package包/類
/** 글 정렬 메서드
 * @param query
 * @param sort
 */
public void sorting(Query query, String sort) {
	if (sort.equals("age-asc")) {
		query.with(new Sort(Sort.Direction.ASC, "_id"));
	} else if (sort.equals("push-desc")) {
		query.with(new Sort(Sort.Direction.DESC, "push"));
	} else if (sort.equals("repost-desc")) {
		query.with(new Sort(Sort.Direction.DESC, "recentRePostDate"));
	} else if (sort.equals("repost-many")) {
		query.with(new Sort(Sort.Direction.DESC, "rePostCount"));
	} else
		query.with(new Sort(Sort.Direction.DESC, "_id"));
}
 
開發者ID:forweaver,項目名稱:forweaver2.0,代碼行數:17,代碼來源:PostDao.java

示例14: listReadHistory

import org.springframework.data.domain.Sort; //導入依賴的package包/類
@Override
public Page<NewsReadHistory> listReadHistory(String id, PageQueryRequest queryRequest) {
	News news = newsRepository.findById(id);
	if (news == null) {
		throw new NewsNotFoundException();
	}
	return newsReadHistoryRepository.findByNews(news,
												new PageRequest(queryRequest.getStart(),
																queryRequest.getLimit(),
																new Sort(Sort.Direction.DESC, "latestReadAt")));
}
 
開發者ID:melthaw,項目名稱:spring-backend-boilerplate,代碼行數:12,代碼來源:NewsServiceImpl.java

示例15: loopContent

import org.springframework.data.domain.Sort; //導入依賴的package包/類
/**
	 *
	 * @Description: 查詢未讀消息
	 * @param
	 * @return  List<PageData>
	 * @throws Exception
	 * @Data: 2017/3/2 下午4:47
	 *
	 */
	private List<PageData> loopContent(PageData pd){
		BasicDBObject fieldsObject=new BasicDBObject();
		//指定返回的字段
		fieldsObject.put("CONTENT", true);
		fieldsObject.put("MESSAGETYPE", true);
		fieldsObject.put("CREATE_TIME", true);
		fieldsObject.put("IMAGE_PATH", true);
		fieldsObject.put("_id", false);

//		Criteria criteria = new Criteria();
//		criteria.orOperator(Criteria.where("TITLE_ID").is(pd.get("TITLE_ID")),
//				Criteria.where("CHANGE_TIME").gt(pd.get("STARTTIME")),
//				Criteria.where("CHANGE_TIME").lte(pd.get("EMDTIME")),
//				Criteria.where("TITLE_TYPE").is(pd.get("TITLE_TYPE")));
//				System.out.print(criteria.toString());
		//查詢條件
		DBObject dbObject = new BasicDBObject();
		dbObject.put("TITLE_ID",pd.get("TITLE_ID"));
		if(StringUtils.isNotBlank(pd.getString("TITLE_TYPE"))){
			dbObject.put("TITLE_TYPE",pd.get("TITLE_TYPE"));
		}

		dbObject.put("CHANGE_TIME",new BasicDBObject("$lt", pd.get("EMDTIME")));
		dbObject.put("CHANGE_TIME",new BasicDBObject("$gte", pd.get("STARTTIME")));

		Query query = new BasicQuery(dbObject,fieldsObject);
		//排序
		query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "CHANGE_TIME")));
		List<PageData> allContent=mongoTemplate.find(query,PageData.class,"IM_CONTENT");
		return allContent;
	}
 
開發者ID:noseparte,項目名稱:Spring-Boot-Server,代碼行數:41,代碼來源:AppCustomerRestful.java


注:本文中的org.springframework.data.domain.Sort類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。