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

The following examples show how to use org.springframework.data.domain.Sort. These examples are extracted from open source projects. 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
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 2
Source Project: mirrorgate   Source File: ReviewRepositoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<ApplicationReviewsDTO> getLastReviewPerApplication(final List<String> names) {

    final Aggregation aggregation = newAggregation(
        match(Criteria.where("appname").in(names)),
        sort(Sort.by(DESC, "timestamp")),
        group("appname", "platform")
            .first("platform").as("platform")
            .first("appname").as("appName")
            .first("appname").as("appId")
            .first("commentId").as("commentId")
    );

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

    return groupResults.getMappedResults();
}
 
Example 3
Source Project: hawkbit   Source File: TargetFilterBeanQuery.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 *
 * @param definition
 * @param queryConfig
 * @param sortPropertyIds
 * @param sortStates
 */
public TargetFilterBeanQuery(final QueryDefinition definition, final Map<String, Object> queryConfig,
        final Object[] sortPropertyIds, final boolean[] sortStates) {
    super(definition, queryConfig, sortPropertyIds, sortStates);
    if (HawkbitCommonUtil.isNotNullOrEmpty(queryConfig)) {
        searchText = (String) queryConfig.get(SPUIDefinitions.FILTER_BY_TEXT);
        if (!StringUtils.isEmpty(searchText)) {
            searchText = String.format("%%%s%%", searchText);
        }
    }

    if (sortStates != null && sortStates.length > 0) {
        // Initalize sort
        sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[0]);
        // Add sort
        for (int tfId = 1; tfId < sortPropertyIds.length; tfId++) {
            sort.and(new Sort(sortStates[tfId] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[tfId]));
        }
    }
}
 
Example 4
Source Project: cms   Source File: WxAccountFansServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<WxAccountFans> getAccountFans(Integer page, int size, WxAccountFans query, Long tagId) {
    Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
    return fansRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (tagId != null && tagId > 0) {
            Join<WxAccountFans, WxFansTag> tagsJoin = root.join("fansTags", JoinType.LEFT);
            predicates.add(criteriaBuilder.equal(tagsJoin.get("tagId"), tagId));
            criteriaQuery.distinct(true);
        }
        if (StringUtils.isNotBlank(query.getNickName())) {
            predicates.add(criteriaBuilder.like(root.get("nickName"), query.getNickName() + "%"));
        }

        return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
    }, pageable);
}
 
Example 5
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
    log.info("start data initialization  ...");
    this.databaseClient.insert()
        .into("posts")
        //.nullValue("id", Integer.class)
        .value("title", "First post title")
        .value("content", "Content of my first post")
        .map((r, m) -> r.get("id", Integer.class))
        .all()
        .log()
        .thenMany(
            this.databaseClient.select()
                .from("posts")
                .orderBy(Sort.by(desc("id")))
                .as(Post.class)
                .fetch()
                .all()
                .log()
        )
        .subscribe(null, null, () -> log.info("initialization is done..."));
}
 
Example 6
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 7
Source Project: hawkbit   Source File: ActionStatusMsgBeanQuery.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parametric Constructor.
 *
 * @param definition
 *            QueryDefinition contains the query properties.
 * @param queryConfig
 *            Implementation specific configuration.
 * @param sortPropertyIds
 *            The properties participating in sort.
 * @param sortStates
 *            The ascending or descending state of sort properties.
 */
public ActionStatusMsgBeanQuery(final QueryDefinition definition, final Map<String, Object> queryConfig,
        final Object[] sortPropertyIds, final boolean[] sortStates) {
    super(definition, queryConfig, sortPropertyIds, sortStates);

    if (isNotNullOrEmpty(queryConfig)) {
        currentSelectedActionStatusId = (Long) queryConfig.get(SPUIDefinitions.MESSAGES_BY_ACTIONSTATUS);
        noMessageText = (String) queryConfig.get(SPUIDefinitions.NO_MSG_PROXY);
    }

    if (sortStates != null && sortStates.length > 0) {
        // Initialize sort
        sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[0]);
        // Add sort
        for (int distId = 1; distId < sortPropertyIds.length; distId++) {
            sort.and(new Sort(sortStates[distId] ? Direction.ASC : Direction.DESC,
                    (String) sortPropertyIds[distId]));
        }
    }
}
 
Example 8
private void applySort(RequestTemplate template, Sort sort) {
	Collection<String> existingSorts = template.queries().get("sort");
	List<String> sortQueries = existingSorts != null ? new ArrayList<>(existingSorts)
			: new ArrayList<>();
	if (!sortParameter.equals("sort")) {
		existingSorts = template.queries().get(sortParameter);
		if (existingSorts != null) {
			sortQueries.addAll(existingSorts);
		}
	}
	for (Sort.Order order : sort) {
		sortQueries.add(order.getProperty() + "," + order.getDirection());
	}
	if (!sortQueries.isEmpty()) {
		template.query(sortParameter, sortQueries);
	}
}
 
Example 9
Source Project: spring-cloud-gcp   Source File: FirestoreRepositoryTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSortQuery() {
	userRepository.findByAgeGreaterThan(0, Sort.by("name")).blockLast();

	ArgumentCaptor<StructuredQuery.Builder> captor =
			ArgumentCaptor.forClass(StructuredQuery.Builder.class);
	verify(template).execute(captor.capture(), eq(User.class));

	StructuredQuery.Builder result = captor.getValue();
	assertThat(result.getOrderByList()).containsExactly(
			Order.newBuilder()
					.setDirection(Direction.ASCENDING)
					.setField(
							FieldReference.newBuilder().setFieldPath("name"))
					.build());
}
 
Example 10
Source Project: SpringAll   Source File: UserService.java    License: MIT License 6 votes vote down vote up
public Page<User> getUserByCondition(int size, int page, User user) {
    Query query = new Query();
    Criteria criteria = new Criteria();

    if (!StringUtils.isEmpty(user.getName())) {
        criteria.and("name").is(user.getName());
    }
    if (!StringUtils.isEmpty(user.getDescription())) {
        criteria.and("description").regex(user.getDescription());
    }

    query.addCriteria(criteria);

    Sort sort = new Sort(Sort.Direction.DESC, "age");
    Pageable pageable = PageRequest.of(page, size, sort);

    List<User> users = template.find(query.with(pageable), User.class);
    return PageableExecutionUtils.getPage(users, pageable, () -> template.count(query, User.class));
}
 
Example 11
Source Project: market   Source File: ShowcaseControllerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getRegionProducts_SortedByAge_PageSize4() throws Exception {
	String sortBy = "age";
	PageRequest request = PageRequest.of(0, 4, Sort.by(Sort.Direction.ASC, sortBy));
	Page<Product> page = new PageImpl<>(
		Arrays.asList(product11, product12, product13, product14),
		request,
		productsRegion1.size());

	given(productService.findByRegion(any(Region.class), pageableCaptor.capture()))
		.willReturn(page);

	mockMvc.perform(
		get("/regions/{regionId}", region1.getId())
			.param("sort", sortBy)
			.param("size", Integer.toString(request.getPageSize())))
		.andExpect(status().isOk())
		.andExpect(view().name("regions"))
		.andExpect(model().attribute("selectedRegion", equalTo(regionDtoAssembler.toModel(region1))))
		.andExpect(model().attribute("regions", contains(regionDtoAssembler.toDtoArray(totalRegions))))
		.andExpect(model().attribute("distilleries", contains(distilleryDtoAssembler.toDtoArray(distilleriesOfRegion1))))
		.andExpect(model().attribute("page", productAssembler.toModel(page)));
	assertThat(pageableCaptor.getValue(), equalTo(request));
}
 
Example 12
Source Project: fw-cloud-framework   Source File: DictServiceImpl.java    License: 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 13
Source Project: sdn-rx   Source File: ReactiveRepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void findWithPageable(@Autowired ReactivePersonRepository repository) {

	Sort sort = Sort.by("name");
	int page = 0;
	int limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person1))
		.verifyComplete();


	sort = Sort.by("name");
	page = 1;
	limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person2))
		.verifyComplete();
}
 
Example 14
Source Project: OpenLRW   Source File: RiskService.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Get RiskScore for a user and a class given
 *
 * @param tenantId
 * @param orgId
 * @param classId
 * @param userId
 * @param date : format 'yyyy-mm-dd' or keyword 'latest'
 * @return Collection<MongoRisk>
 */
public Collection<MongoRisk> getRisksForUserAndClass(
        final String tenantId, final String orgId, final String classId,
        final String userId, final String date, final int limit
){
    if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(orgId) || StringUtils.isBlank(userId) || StringUtils.isBlank(classId))
        throw new IllegalArgumentException();

    Collection<MongoRisk> mongoRisks;

    Query query = new Query();
    query.with(Sort.by("dateTime").descending()); // Order by date: the most recent
    query.addCriteria(where("userSourcedId").is(userId).and("classSourcedId").is(classId).and("orgId").is(orgId).and("tenantId").is(tenantId));

    if (limit > 0)
        query.limit(limit);

    this.dayCriteria(query, date);

    mongoRisks = mongoOps.find(query, MongoRisk.class);

    if (!mongoRisks.isEmpty())
        return new ArrayList<>(mongoRisks);

    throw new OneRosterNotFoundException("Risks not found.");
}
 
Example 15
Source Project: runscore   Source File: MerchantService.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
public PageResult<MerchantVO> findMerchantByPage(MerchantQueryCondParam param) {
	Specification<Merchant> spec = new Specification<Merchant>() {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public Predicate toPredicate(Root<Merchant> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
			List<Predicate> predicates = new ArrayList<Predicate>();
			if (StrUtil.isNotBlank(param.getName())) {
				predicates.add(builder.equal(root.get("name"), param.getName()));
			}
			return predicates.size() > 0 ? builder.and(predicates.toArray(new Predicate[predicates.size()])) : null;
		}
	};
	Page<Merchant> result = merchantRepo.findAll(spec,
			PageRequest.of(param.getPageNum() - 1, param.getPageSize(), Sort.by(Sort.Order.desc("createTime"))));
	PageResult<MerchantVO> pageResult = new PageResult<>(MerchantVO.convertFor(result.getContent()),
			param.getPageNum(), param.getPageSize(), result.getTotalElements());
	return pageResult;
}
 
Example 16
Source Project: WeBASE-Front   Source File: EventController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "getNewBlockEventInfo",
        notes = "get registered NewBlockEvent info by page")
@GetMapping(value = {"newBlockEvent/list/{groupId}/{pageNumber}/{pageSize}",
        "newBlockEvent/list/{groupId}"})
public BasePageResponse getNewBlockEventInfo(@PathVariable("groupId") Integer groupId,
                                             @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                                             @PathVariable(value = "pageSize", required = false) Integer pageSize) {
    log.debug("start getNewBlockEventInfo. groupId:{}", groupId);
    List<NewBlockEventInfo> resList;
    if (pageNumber == null || pageSize == null) {
         resList = eventService.getNewBlockInfoList(groupId);
    } else {
        if (pageNumber < 1) {
            return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0);
        }
        Pageable pageable = new PageRequest(pageNumber - 1, pageSize,
                new Sort(Sort.Direction.DESC, "createTime"));
        resList = eventService.getNewBlockInfoList(groupId, pageable);
    }
    log.debug("end getNewBlockEventInfo resList count. {}", resList.size());
    return new BasePageResponse(ConstantCode.RET_SUCCESS, resList, resList.size());
}
 
Example 17
Source Project: WeBASE-Front   Source File: EventController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "getContractEventInfo",
        notes = "get registered contract event info by page")
@GetMapping(value = {"contractEvent/list/{groupId}/{pageNumber}/{pageSize}",
        "contractEvent/list/{groupId}"})
public BasePageResponse getContractEventInfo(@PathVariable("groupId") Integer groupId,
                                             @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                                             @PathVariable(value = "pageSize", required = false) Integer pageSize) {
    log.debug("start getContractEventInfo.");
    List<ContractEventInfo> resList;
    if (pageNumber == null || pageSize == null) {
        resList = eventService.getContractEventInfoList(groupId);
    } else {
        if (pageNumber < 1) {
            return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0);
        }
        Pageable pageable = new PageRequest(pageNumber - 1, pageSize,
                new Sort(Sort.Direction.DESC, "createTime"));
        resList = eventService.getContractEventInfoList(groupId, pageable);
    }
    log.debug("end getContractEventInfo resList count. {}", resList.size());
    return new BasePageResponse(ConstantCode.RET_SUCCESS, resList, resList.size());
}
 
Example 18
Source Project: biliob_backend   Source File: AuthorServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<AuthorVisitRecord> listMostVisitAuthorId(Integer days, Integer limit) {
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -days);
    List<AuthorVisitRecord> results = mongoTemplate.aggregate(
            Aggregation.newAggregation(Aggregation.match(where("date").gt(c.getTime())),
                    Aggregation.group("mid").count().as("count").first("mid").as("mid"),
                    Aggregation.sort(Sort.Direction.DESC, "count"), Aggregation.limit(limit)),
            "author_visit", AuthorVisitRecord.class).getMappedResults();
    Query q = Query.query(Criteria.where("mid")
            .in(results.stream().map(AuthorVisitRecord::getMid).collect(Collectors.toList())));
    q.fields().include("name").include("mid");
    List<Author> authorList = mongoTemplate.find(q, Author.class);
    for (AuthorVisitRecord result : results) {
        for (Author author : authorList) {
            if (result.getMid().equals(author.getMid())) {
                result.setName(author.getName());
            }
        }

    }
    return results;
}
 
Example 19
Source Project: ZTuoExchange_framework   Source File: SysHelpService.java    License: MIT License 5 votes vote down vote up
public Page<SysHelp> findByCate(int pageNo,int pageSize,String cate){
    Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "sort"));
    Pageable pageable = new PageRequest(pageNo - 1, pageSize, sort);
    Specification specification = new Specification() {
        List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();

        @Override
        public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
            predicates.add(criteriaBuilder.equal(root.get("SysHelpClassification"),cate));
            predicates.add(criteriaBuilder.equal(root.get("isTop"),"0"));
            return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
        }
    };
    return sysHelpDao.findAll(specification,pageable);
}
 
Example 20
Source Project: hermes   Source File: PropertiesServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Page<Properties> queryByCondition(final Properties properties, final String typeId,String page, String size) throws Exception {
	 Pageable pageable = new PageRequest(Integer.valueOf(Strings.empty(page, "0")), Integer.valueOf(Strings.empty(size, "10")), new Sort(Direction.DESC,  "createTime"));
	 return  propertiesRepository.findAll(new Specification<Properties>() {
		@Override
		public Predicate toPredicate(Root<Properties> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
			List<Predicate> list = new ArrayList<Predicate>();
			if (StringUtils.isNotEmpty(properties.getCode())) {
				list.add(cb.like(root.<String>get("code"), "%"+properties.getCode().trim()+"%"));
			}
			if (StringUtils.isNotEmpty(properties.getName())) {
				list.add(cb.like(root.<String>get("name"), "%"+properties.getName().trim()+"%"));
			}
			if (StringUtils.isNotEmpty(properties.getStatus())) {
				list.add(cb.equal(root.<String>get("status"), properties.getStatus().trim()));
			}
			if (StringUtils.isNotEmpty(typeId)) {
				list.add(cb.equal(root.<String>get("type").<String>get("id"), typeId));
			}
			Dictionary  dict = dictionaryRepository.findByCodeAndStatus(HermesConstants.PLAT_TYPE,HermesConstants.CODE_00);
			if(dict != null){
			     list.add(cb.notEqual(root.<String>get("type").<String>get("id"), dict.getId()));
			}
			return cb.and(list.toArray(new Predicate[list.size()]));
		}
	},pageable);
}
 
Example 21
Source Project: flash-waimai   Source File: MongoRepository.java    License: MIT License 5 votes vote down vote up
public <T> Page<T> queryPage(Page<T> page, Class<T> klass, Map<String, Object> params) {
    Pageable pageable = PageRequest.of(page.getCurrent() - 1, page.getSize(), Sort.Direction.DESC, "id");
    Query query = new Query();
    if (params != null && !params.isEmpty()) {
        Criteria criteria = criteria(params);
        query = Query.query(criteria);
    }
    List<T> list = mongoTemplate.find(query.with(pageable), klass);
    Long count = count(klass, params);
    page.setTotal(count.intValue());
    page.setRecords(list);
    return page;
}
 
Example 22
Source Project: Spring-Boot-Book   Source File: ProductControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getAll() {
    Iterable<Product> list = productRepository.findAll(Sort.by("id").ascending());
    for (Product product : list) {
        System.out.println(product);
    }

}
 
Example 23
private void addSort(Query query, DataTablesInput input) {
    query.skip(input.getStart());
    query.limit(input.getLength());

    if (isEmpty(input.getOrder())) return;

    List<Sort.Order> orders = input.getOrder().stream()
            .filter(order -> isOrderable(input, order))
            .map(order -> toOrder(input, order)).collect(toList());
    query.with(by(orders));
}
 
Example 24
Source Project: halo   Source File: PostController.java    License: GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("{postId:\\d+}/comments/top_view")
public Page<CommentWithHasChildrenVO> listTopComments(@PathVariable("postId") Integer postId,
                                                      @RequestParam(name = "page", required = false, defaultValue = "0") int page,
                                                      @SortDefault(sort = "createTime", direction = DESC) Sort sort) {

    return postCommentService.pageTopCommentsBy(postId, CommentStatus.PUBLISHED, PageRequest.of(page, optionService.getCommentPageSize(), sort));
}
 
Example 25
Source Project: portal-de-servicos   Source File: ServicosEmDestaque.java    License: MIT License 5 votes vote down vote up
private List<ServicoXML> completaSevicosAteOLimite(Stream<ServicoXML> servicosBase, int quantidade) {
    PageRequest pagina = new PageRequest(0, quantidade, new Sort(DESC, "nome"));

    Stream<ServicoXML> outrosServicos = servicos.findAll(pagina).getContent()
            .stream()
            .filter(s -> !destaques.getServicos().contains(s.getId()));

    return concat(servicosBase, outrosServicos)
            .limit(quantidade)
            .collect(toList());
}
 
Example 26
Source Project: blog-sharon   Source File: FrontCommentController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 加载评论
 *
 * @param page 页码
 * @param post 当前文章
 * @return List
 */
@GetMapping(value = "/loadComment")
@ResponseBody
public List<Comment> loadComment(@RequestParam(value = "page") Integer page,
                                 @RequestParam(value = "post") Post post) {
    Sort sort = new Sort(Sort.Direction.DESC, "commentDate");
    Pageable pageable = PageRequest.of(page - 1, 10, sort);
    List<Comment> comments = commentService.findCommentsByPostAndCommentStatus(post, pageable, CommentStatusEnum.PUBLISHED.getCode()).getContent();
    return comments;
}
 
Example 27
Source Project: biliob_backend   Source File: VideoServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * get most popular tag
 *
 * @return most popular tag
 */
@Override
public List listMostPopularTag() {
    return mongoTemplate
            .aggregate(
                    Aggregation.newAggregation(
                            Aggregation.unwind("tag"),
                            Aggregation.group("tag").sum("cView").as("totalView"),
                            Aggregation.sort(Sort.Direction.DESC, "totalView"),
                            Aggregation.limit(100)),
                    "video",
                    Map.class)
            .getMappedResults();
}
 
Example 28
Source Project: rpi   Source File: RpiWeatherApiController.java    License: Apache License 2.0 5 votes vote down vote up
public ResponseEntity<List<RpiWeatherItem>> findWeatherItems(@ApiParam(value = "Page Number") @RequestParam(value = "page", required = true) final Integer page, @ApiParam(value = "Page Size") @RequestParam(value = "size", required = true) final Integer size) {
    final PageRequest page1 = new PageRequest(
            page, size, Sort.Direction.DESC, "id"
    );


    return new ResponseEntity<List<RpiWeatherItem>>(rpiWeatherRepository.findAll(page1).getContent(), HttpStatus.OK);
}
 
Example 29
Source Project: tutorials   Source File: UserRepositoryCommon.java    License: MIT License 5 votes vote down vote up
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() {
    userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
    userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
    userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));

    userRepository.findAll(Sort.by(Sort.Direction.ASC, "name"));

    List<User> usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)"));

    assertThat(usersSortByNameLength.get(0)
      .getName()).isEqualTo(USER_NAME_ADAM);
}
 
Example 30
Source Project: ZTuoExchange_framework   Source File: MongoBaseService.java    License: MIT License 5 votes vote down vote up
/**
 * mongodb分页排序查询
 * @param pageParam:分页参数(pageNo、pageSize、order、direction)
 * @param query
 * @param cla
 * @param collectionName
 * @return
 */
public Pagenation page(PageParam pageParam , Query query, Class<T> cla, String collectionName ){
    if(pageParam.getOrders()!=null&&pageParam.getDirection()!=null) {
        query.with(new Sort(pageParam.getDirection(),pageParam.getOrders()));
    }
    long total  = mongoTemplate.count(query,cla,collectionName);
    query.limit(pageParam.getPageSize()).skip((pageParam.getPageNo()-1)*pageParam.getPageSize());
    List<T> list = mongoTemplate.find(query,cla,collectionName);
    long consult = total/pageParam.getPageSize() ;
    long residue = total%pageParam.getPageSize();
    long totalPage = residue == 0 ?consult :(consult+1) ;
    Pagenation pagenation = new Pagenation(pageParam);
    return pagenation.setData(list,total,totalPage);
}