/** * 分词 查询 商品名称 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)); }
@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(); }
/** * 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)); }
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(); }
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); }
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"); } }
/** * 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); } }
/** * 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); }
@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"; }
@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; }
@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); }
/** * 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); } }
/** 글 정렬 메서드 * @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")); }
@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"))); }
/** * * @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; }
@Test public void testPage() { int page = 0, size = 10; Sort sort = new Sort(Sort.Direction.DESC, "id"); Pageable pageable = new PageRequest(page, size, sort); Page<User> all = userRepository.findAll(pageable); all.forEach(e -> log.info("testPage:{}", e)); }
@Override public Page<User> queryArchivedUsers(UserQueryRequest queryRequest) { int start = queryRequest.getStart(); int limit = queryRequest.getLimit(); Query query = buildQuery(queryRequest); query.addCriteria(Criteria.where("deleted").is(true)); PageRequest pageable = new PageRequest(start, limit, new Sort(Sort.Direction.DESC, "deletedAt")); query.with(pageable); long count = mongoTemplate.count(query, User.class); List<User> list = mongoTemplate.find(query, User.class); return new PageImpl<>(list, pageable, count); }
@Override public Page<UserOrg> findAll(final Collection<GroupOrg> requiredGroups, final Set<String> companies, final String criteria, final Pageable pageable) { // Create the set with the right comparator final List<Sort.Order> orders = IteratorUtils.toList(ObjectUtils.defaultIfNull(pageable.getSort(), new ArrayList<Sort.Order>()).iterator()); orders.add(DEFAULT_ORDER); final Sort.Order order = orders.get(0); Comparator<UserOrg> comparator = ObjectUtils.defaultIfNull(COMPARATORS.get(order.getProperty()), DEFAULT_COMPARATOR); if (order.getDirection() == Direction.DESC) { comparator = Collections.reverseOrder(comparator); } final Set<UserOrg> result = new TreeSet<>(comparator); // Filter the users traversing firstly the required groups and their members, the companies, then the criteria final Map<String, UserOrg> users = findAll(); if (requiredGroups == null) { // No constraint on group addFilteredByCompaniesAndPattern(users.keySet(), companies, criteria, result, users); } else { // User must be within one the given groups for (final GroupOrg requiredGroup : requiredGroups) { addFilteredByCompaniesAndPattern(requiredGroup.getMembers(), companies, criteria, result, users); } } // Apply in-memory pagination return inMemoryPagination.newPage(result, pageable); }
@Override public String selectAll(TableDescription table, String whereClause, Pageable page) { Sort sort = page.getSort() != null ? page.getSort() : sortById(table); return format("%s OFFSET %d ROWS FETCH NEXT %d ROW ONLY", selectAll(table, whereClause, sort), page.getOffset(), page.getPageSize()); }
@Override public Page<AuthEvent> queryPage(AuthEventQueryRequest queryRequest) { int start = queryRequest.getStart(); int limit = queryRequest.getLimit(); Query query = buildQuery(queryRequest); PageRequest pageable = new PageRequest(start, limit, new Sort(Sort.Direction.DESC, "loginAt")); query.with(pageable); long count = mongoTemplate.count(query, AuthEvent.class); List<AuthEvent> list = mongoTemplate.find(query, AuthEvent.class); return new PageImpl<>(list, pageable, count); }
public RestResponsePage(int offset, int size, long totalElements, List<T> content, List<Sort.Order> sort) { this.offset = offset; this.size = size; this.totalElements = totalElements; this.content = content; this.sort = sort; }
private List<Trip> findSortedBy(String property){ Sort sort = Sort.by(Direction.DESC, property); PageRequest request = PageRequest.of(0, HOMEPAGE_COLUMN_LENGHT, sort); Page<Trip> page = tripRepository.findAll(request); if (log.isDebugEnabled()) log.debug("Result for {} page: {} ", property, page ); return page.getContent(); }
@Override public List<File> listFilesByPage(int pageIndex, int pageSize) { Page<File> page = null; List<File> list = null; Sort sort = new Sort(Direction.DESC,"uploadDate"); Pageable pageable = new PageRequest(pageIndex, pageSize, sort); page = fileRepository.findAll(pageable); list = page.getContent(); return list; }
@Override public List<Story> findHotStoriesOfGroup(String groupId) { Query query = new Query(); query.with(new Sort(Sort.Direction.DESC, "this.comments.length")); query.addCriteria(Criteria.where("groupId").is(groupId)); return mongoTemplate.find(query, Story.class); }
/** * Is not supposed to be called from external of interface (might be private in Java 9) * * @param sortValue SortValue to get SortField from * @param sortDirection Direction of sorting from request * @return A field sorted for jOOQ */ @NotNull default SortField<?> convertTableFieldToSortField(SortValue sortValue, Sort.Direction sortDirection) { if (sortDirection == Sort.Direction.ASC) { return sortValue.getSortField(SortOrder.ASC); } else { return sortValue.getSortField(SortOrder.DESC); } }
@RequestMapping(value = "search", method = RequestMethod.GET) public ModelAndView findDishes(@QuerydslPredicate(root = Dish.class) Predicate predicate, @PageableDefault(sort = {"date"}, direction = Sort.Direction.DESC) Pageable pageable, ModelAndView modelAndView) { Sort realSort = pageable.getSort().and(new Sort(Sort.Direction.ASC, "id")); PageRequest pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), realSort); Page<Dish> page = dishRepo.findAll(predicate, pageRequest); List<DishWebDTO> dishes = page.getContent().stream().map(dishDtoFactory::create).collect(Collectors.toList()); modelAndView.addObject("page", page); modelAndView.addObject("dishes", dishes); modelAndView.addObject("labels", getLabelsFromDishes()); modelAndView.addObject("categories", getCategoriesFromDishes()); modelAndView.addObject("mensas", mensaRepo.findAllByOrderByName()); modelAndView.setViewName("search"); return modelAndView; }
@Override public List<Event> findEvents(UUID tenantId, EntityId entityId, String eventType, TimePageLink pageLink) { Specification<EventEntity> timeSearchSpec = JpaAbstractSearchTimeDao.<EventEntity>getTimeSearchPageSpec(pageLink, "id"); Specification<EventEntity> fieldsSpec = getEntityFieldsSpec(tenantId, entityId, eventType); Sort.Direction sortDirection = pageLink.isAscOrder() ? Sort.Direction.ASC : Sort.Direction.DESC; Pageable pageable = new PageRequest(0, pageLink.getLimit(), sortDirection, ID_PROPERTY); return DaoUtil.convertDataList(eventRepository.findAll(where(timeSearchSpec).and(fieldsSpec), pageable).getContent()); }
@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); query.setFirstResult(pageable.getOffset()); 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); } }
private static Sort.Order generateOrder(String f) { Sort.Order order = null; String[] ff = f.split("_"); if(ff.length>=2) { if(ff[1].equals("d")) { order = new Sort.Order(Sort.Direction.DESC,ff[0]); } else { order = new Sort.Order(Sort.Direction.ASC,ff[0]); } return order; } order = new Sort.Order(f); return order; }
public void doResourceMigration(final ResourceRepository resourceRepository, final GraphResourceRepository resourceHierarchicalRepository, final int pageSize) { int numOfResourcesSaved = 0; Pageable pageRequest = new PageRequest(0, pageSize, new Sort("id")); long numOfResourceEntitiesToMigrate = resourceRepository.count(); Page<ResourceEntity> pageOfResources; do { pageOfResources = resourceRepository.findAll(pageRequest); List<ResourceEntity> resourceListToSave = pageOfResources.getContent(); numOfResourcesSaved += pageOfResources.getNumberOfElements(); resourceListToSave.forEach(item -> { // Clear the auto-generated id field prior to migrating to graphDB item.setId((long) 0); LOGGER.trace("doResourceMigration Resource-Id: {} Zone-name: {} Zone-id: {}", item.getResourceIdentifier(), item.getZone().getName(), item.getZone().getId()); }); resourceHierarchicalRepository.save(resourceListToSave); LOGGER.info("Total resources migrated so far: {}/{}", numOfResourcesSaved, numOfResourceEntitiesToMigrate); pageRequest = pageOfResources.nextPageable(); } while (pageOfResources.hasNext()); LOGGER.info("Number of resource entities migrated: {}", numOfResourcesSaved); LOGGER.info("Resource migration to Titan completed."); }
@Test public void supportsProjectionInCombinationWithPagination() { Page<CustomerProjection> page = customers .findPagedProjectedBy(new PageRequest(0, 1, new Sort(Direction.ASC, "lastname"))); assertThat(page.getContent().get(0).getFirstname(), is("Carter")); }
@GetMapping public Collection getAllCountries( @RequestParam(name = "sort", required = false) String sort) { final List<Country> sortedCountries; // Get query parameter if ("name,desc".equals(sort)) { sortedCountries = countryRepo.findAll( new Sort(Sort.Direction.DESC, "name")); } else { // default sorting: name (ascending) sortedCountries = countryRepo.findAll( new Sort("name")); } return sortedCountries; }
@Override public Page<FileObject> listFileObject(DefaultFileObjectQueryParameter queryParameter, User user) { String sortedBy = queryParameter.getSortedBy(); if (StringUtils.isEmpty(sortedBy)) { sortedBy = "uploadedAt"; } return fileObjectRepository.findPage(queryParameter, new PageRequest(queryParameter.getStart(), queryParameter.getLimit(), new Sort(Sort.Direction.ASC, sortedBy))); }
@Override public E findOne(Specification<E> spec, LockModeType lockMode) { try { return getQuery(spec, (Sort) null).setLockMode(lockMode).getSingleResult(); } catch (NoResultException e) { return null; } }
/** * Fetch all events with their associated readings. LimitExceededException (HTTP 413) if the * number of events exceeds the current max limit. ServiceException (HTTP 503) for unknown or * unanticipated issues. * * @return list of events * @throws ServiceException (HTTP 503) for unknown or unanticipated issues * @throws LimitExceededException (HTTP 413) if the number of events exceeds the current max limit */ @RequestMapping(method = RequestMethod.GET) @Override public List<Event> events() { if (eventRepos != null && eventRepos.count() > maxLimit) throw new LimitExceededException(LIMIT_ON_EVENT); try { Sort sort = new Sort(Sort.Direction.DESC, "_id"); return eventRepos.findAll(sort); } catch (Exception e) { logger.error(ERR_GETTING + e.getMessage()); throw new ServiceException(e); } }
/** * 物品统计 * url例子/statistics?page=10&size=50&sort=marketPrice,desc * * @param pageable size默认50,sort默认marketPrice倒序 * @return */ @GetMapping("/statistics") public List<ItemStatisticDTO> findStatistics(@PageableDefault(value = 50, sort = {"marketPrice"}, direction = Sort.Direction.DESC) Pageable pageable) { // 检查返回size,避免返回过大数据 int maxSize = 100; if (pageable.getPageSize() > maxSize) { throw new IllegalArgumentException("超过最大返回数据量:" + maxSize); } return statisticService.findAllItemStatistic(pageable); }
@Override public Page<Article> getPublishedArticleByPage(int pageNum, int pageSize) { Page<Article> articles = articleRepository.findByStatus( new PageRequest(pageNum, pageSize, Sort.Direction.DESC, "id"), 2); articles.forEach(article -> { int moreIndex = article.getContent().indexOf("<!--more-->"); if (moreIndex > 0) { article.setContent(article.getContent().substring(0, moreIndex)); } }); return articles; }
@Override public Iterable<D> findAll(Sort sort) { Assert.notNull(sort, "sort must not be null"); Iterator<Sort.Order> iter = sort.iterator(); String query = findAllQuery + "ORDER BY "; while (iter.hasNext()) { Sort.Order order = iter.next(); query = query + order.getProperty() + " " + order.getDirection(); if (iter.hasNext()) { query = query + ", "; } } return jdbcTemplate.query(query, rowMapper); }
/** * 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); }
@Override public Page<Posts> getPostsByPage(String type, String search, int pageNo, int length) { List<Sort.Order> orders = new ArrayList<>(); orders.add(new Sort.Order(Sort.Direction.DESC, "top")); orders.add(new Sort.Order(Sort.Direction.DESC, "id")); Sort sort = new Sort(orders); PageRequest pageable = new PageRequest(pageNo, length, sort); Specification<Posts> specification = new Specification<Posts>() { @Override public Predicate toPredicate(Root<Posts> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { Path<Boolean> $top = root.get("top"); Path<Boolean> $good = root.get("good"); Path<String> $title = root.get("title"); ArrayList<Predicate> list = new ArrayList<>(); if (type != null && type.equals("good")) list.add(criteriaBuilder.equal($good, true)); if (type != null && type.equals("top")) list.add(criteriaBuilder.equal($top, true)); if (search != null && search != "") list.add(criteriaBuilder.like($title, "%" + search + "%")); Predicate predicate = criteriaBuilder.and(list.toArray(new Predicate[list.size()])); return predicate; } }; Page<Posts> page = repository.findAll(specification, pageable); return page; }