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

The following are top voted examples for showing how to use org.springframework.data.domain.PageRequest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-backend-boilerplate   File: UserRepositoryImpl.java   Source Code and License 11 votes vote down vote up
@Override
public Page<User> queryPage(SysRole role, UserQueryRequest queryRequest) {
	int start = queryRequest.getStart();
	int limit = queryRequest.getLimit();
	Query query = new Query();
	query.addCriteria(Criteria.where("roles").in(role));
	if (!StringUtils.isEmpty(queryRequest.getUsername())) {
		query.addCriteria(Criteria.where("username").regex(queryRequest.getUsername()));
	}
	query.addCriteria(Criteria.where("deleted").ne(true));

	PageRequest pageable = new PageRequest(start, limit, new Sort(Sort.Direction.DESC, "username"));
	query.with(pageable);
	long count = mongoTemplate.count(query, User.class);
	List<User> list = mongoTemplate.find(query, User.class);

	return new PageImpl<>(list, pageable, count);
}
 
Example 2
Project: forweaver2.0   File: PostDao.java   Source Code and License 9 votes vote down vote up
/** 자기가 진행중인 저장소의 글을 검색함.
 * @param privateAndMassageTags
 * @param search
 * @param sort
 * @param page
 * @param size
 * @return
 */
public List<Post> getMyRepositoryPosts(List<String> privateAndMassageTags, String search, 
		String sort, int page,int size) {
	Criteria criteria = new Criteria();

	criteria.and("tags").in(privateAndMassageTags);

	if (search != null)
		criteria.andOperator(new Criteria().orOperator(
				Criteria.where("title").regex(search),
				Criteria.where("content").regex(search)));

	this.filter(criteria, sort);

	Query query = new Query(criteria);
	query.with(new PageRequest(page - 1, size));

	this.sorting(query, sort);
	return mongoTemplate.find(query, Post.class);
}
 
Example 3
Project: owl   File: ServicesUtils.java   Source Code and License 8 votes vote down vote up
/**
 * 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));
}
 
Example 4
Project: pathological-reports   File: UserService.java   Source Code and License 8 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public PageWrapper<User> findBy(FindUserDTO dto, int page, int size) {
	List<String> roleStr = null;
	String usernameOrEmail;

	if (dto.getRole() == null) {

		if (UserUtils.isAdmin())
			roleStr = Arrays.asList(RoleEnum.PROFESSOR.name(), RoleEnum.STUDENT.name());

		else if (UserUtils.isProfessor())
			roleStr = Arrays.asList(RoleEnum.STUDENT.name());

	} else {
		roleStr = Arrays.asList(dto.getRole().name());
	}

	usernameOrEmail = StringUtils.isEmpty(dto.getUsernameOrEmail()) ? "%%" : "%".concat(dto.getUsernameOrEmail().toLowerCase()).concat("%");

	Pageable pageable = new PageRequest(page, size);
	Page<User> pageInterface = userRepository.findBy(roleStr, usernameOrEmail, pageable);

	return new PageWrapper(pageInterface.getContent(), pageable, pageInterface.getTotalElements());
}
 
Example 5
Project: travel-agency   File: SmsConversationService.java   Source Code and License 7 votes vote down vote up
public void saveAndBroadcast(InboundSmsMessage smsMessage){
    log.info("Inbound message received {}", smsMessage);
    
    inboundSmsMessageRepository.save(smsMessage);
    
    Pageable page = (Pageable) PageRequest.of(0, 1, Direction.DESC, "date");
    List<Conversation> conversations = conversationRepository.findByPhoneNumber(smsMessage.getMsisdn(), page);
    
    if( ! conversations.isEmpty()){
        Conversation conversation =  conversations.get(0);
        Optional<Participant> user = conversation.findParticipantByPhone(smsMessage.getMsisdn());
        
        if(user.isPresent()){
            ConversationMessage conversationMessage = createConversationMessage(smsMessage, conversation, user.get());
            broadcastMessage(conversationMessage);
        }else{
            log.warn("No participant found associated with {} in {}", smsMessage.getMsisdn(), conversation.getId());
        }
            
    }else{
        log.warn("No conversation found associated with {}", smsMessage.getMsisdn());
    }
}
 
Example 6
Project: spring-boot-elastcsearch-example   File: GoodsEsDocService.java   Source Code and License 7 votes vote down vote up
/**
 *
 *
 *
 * @param pageNumber
 * @param pageSize
 * @param searchContent
 * @return
 */
public List<GoodsModel> searchGoods(Integer pageNumber,
                                    Integer pageSize,
                                    String searchContent) {
    // 分页参数
    Pageable pageable = new PageRequest(pageNumber, pageSize);

    // Function Score Query
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("goodsName", searchContent)),ScoreFunctionBuilders.weightFactorFunction(1000))
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)),ScoreFunctionBuilders.weightFactorFunction(1000));

    // 创建搜索 DSL 查询
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withPageable(pageable)
            .withQuery(functionScoreQueryBuilder).build();

    logger.info("\n searchGoods(): searchContent [" + searchContent + "] \n DSL  = \n " + searchQuery.getQuery().toString());

    Page<GoodsModel> searchPageResults = goodsESDocRepository.search(searchQuery);
    return searchPageResults.getContent();
}
 
Example 7
Project: forweaver2.0   File: PostDao.java   Source Code and License 6 votes vote down vote up
/** 관리자가 글을 불러올 때
 * @param tags
 * @param search
 * @param writer
 * @param sort
 * @param page
 * @param size
 * @return
 */
public List<Post> getPostsAsAdmin(List<String> tags, String search, Weaver writer, String sort,
		int page, int size) {
	Criteria criteria = new Criteria();

	if (search != null)
		criteria.orOperator(new Criteria("title").regex(search),
				new Criteria("content").regex(search));

	if (tags != null)
		criteria.and("tags").all(tags);
	if (writer != null)
		criteria.and("writer").is(writer);

	this.filter(criteria, sort);

	Query query = new Query(criteria);

	query.with(new PageRequest(page - 1, size));
	this.sorting(query, sort);

	return mongoTemplate.find(query, Post.class);
}
 
Example 8
Project: forweaver2.0   File: RepositoryDao.java   Source Code and License 6 votes vote down vote up
/** 저장소를 검색
 * @param tags
 * @param search
 * @param creator
 * @param sort
 * @param page
 * @param size
 * @return
 */
public List<Repository> getRepositories( 
		List<String> tags,
		String search,
		String sort,
		int page, 
		int size) {
	Criteria criteria = new Criteria();
	
	if(search != null && search.length()>0)
		criteria.orOperator(new Criteria("name").regex(search),
				new Criteria("description").regex(search));
	
	if(tags != null)
		criteria.and("tags").all(tags);
	
	this.filter(criteria, sort);
	
	Query query = new Query(criteria);
	query.with(new PageRequest(page-1, size));

	this.sorting(query, sort);
	return mongoTemplate.find(query, Repository.class);
}
 
Example 9
Project: bootstrap   File: PaginationJsonTest.java   Source Code and License 6 votes vote down vote up
/**
 * Sorted direction with ordering and corresponding ORM column.
 */
@Test
public void getPageRequestFullOrderingMixProvider() {
	// create a mock URI info with pagination informations
	final UriInfo uriInfo = newUriInfo();
	uriInfo.getQueryParameters().add(DataTableAttributes.PAGE_LENGTH, "100");
	uriInfo.getQueryParameters().add("sidx", "col1");
	uriInfo.getQueryParameters().add("sortd", "asc");
	final Map<String, String> map = Collections.singletonMap("col1", "colOrm");
	final PageRequest pageRequest = paginationJson.getPageRequest(uriInfo, map);
	Assert.assertNotNull(pageRequest);
	Assert.assertNotNull(pageRequest.getSort());
	Assert.assertEquals(0, pageRequest.getOffset());
	Assert.assertEquals(0, pageRequest.getPageNumber());
	Assert.assertNull(pageRequest.getSort().getOrderFor("colOrm?"));
	Assert.assertNotNull(pageRequest.getSort().getOrderFor("colOrm"));
	Assert.assertEquals(Direction.ASC, pageRequest.getSort().getOrderFor("colOrm").getDirection());
	Assert.assertTrue(pageRequest.getSort().getOrderFor("colOrm").isIgnoreCase());
	Assert.assertEquals(100, pageRequest.getPageSize());
}
 
Example 10
Project: esup-ecandidat   File: CandidatController.java   Source Code and License 6 votes vote down vote up
/**
 * @param value
 * @param inclureDossierOtherYears
 * @param exactSearch
 * @return la liste des compte grace a un filtre pour la recherche de compte candidat
 */
public List<CompteMinima> getCptMinByFilter(String value, final Boolean inclureDossierOtherYears,
		final Boolean exactSearch) {
	if (!exactSearch) {
		value = "%" + value + "%";
	}
	if (inclureDossierOtherYears) {
		return compteMinimaRepository.findByFilterAllYears(value,
				new PageRequest(0, ConstanteUtils.NB_MAX_RECH_CPT_MIN));
	} else {
		Campagne campagne = campagneController.getCampagneActive();
		if (value == null || campagne == null) {
			return new ArrayList<>();
		}
		return compteMinimaRepository.findByFilter(campagne.getCodCamp(), value,
				new PageRequest(0, ConstanteUtils.NB_MAX_RECH_CPT_MIN));
	}
}
 
Example 11
Project: bootstrap   File: PaginationJsonTest.java   Source Code and License 6 votes vote down vote up
/**
 * Sorted direction with ordering and corresponding ORM column.
 */
@Test
public void getPageRequestIdentityMapping() {
	// create a mock URI info with pagination informations
	final UriInfo uriInfo = newUriInfo();
	uriInfo.getQueryParameters().add("sidx", "col1");
	uriInfo.getQueryParameters().add("sortd", "asc");
	final Map<String, String> map = Collections.singletonMap("*", "*");
	final PageRequest pageRequest = paginationJson.getPageRequest(uriInfo, map);
	Assert.assertNotNull(pageRequest);
	Assert.assertNotNull(pageRequest.getSort());
	Assert.assertEquals(0, pageRequest.getOffset());
	Assert.assertEquals(0, pageRequest.getPageNumber());
	Assert.assertNull(pageRequest.getSort().getOrderFor("col1?"));
	Assert.assertNotNull(pageRequest.getSort().getOrderFor("col1"));
	Assert.assertEquals(Direction.ASC, pageRequest.getSort().getOrderFor("col1").getDirection());
	Assert.assertTrue(pageRequest.getSort().getOrderFor("col1").isIgnoreCase());
	Assert.assertEquals(10, pageRequest.getPageSize());
}
 
Example 12
Project: poppynotes   File: NoteRepositoryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFindByUserIdSorted_withValidQuery_shouldReturnCorrectSortedByPinnedAndLastEditedDescending() {

	List<Note> firstFive = dao.findByUserIdSorted(1l, new PageRequest(0, 5));

	assertEquals("check latest pinned", "1-pinned-latest", firstFive.get(0).getTitle());
	assertEquals("check second pinned", "2-pinned-second", firstFive.get(1).getTitle());
	assertEquals("check third pinned", "3-pinned-third", firstFive.get(2).getTitle());
	assertEquals("check real latest non-pinned", "1latest", firstFive.get(3).getTitle());
	assertEquals("check second non-pinned", "2second", firstFive.get(4).getTitle());

	List<Note> secondFive = dao.findByUserIdSorted(1l, new PageRequest(1, 5));

	assertEquals("check third", "3thrid", secondFive.get(0).getTitle());
	assertEquals("check fourth", "4fourth", secondFive.get(1).getTitle());
	assertEquals("check fifth", "5fifth", secondFive.get(2).getTitle());
	assertEquals("check second oldest", "second oldest", secondFive.get(3).getTitle());
	assertEquals("check oldest",
			"oldest-non-pinned. Capicola kevin ham hock, pancetta ribeye beef ribs short loin pork loin sirloin tail pig porchetta boudin. Chuck porchetta meatloaf, beef ham swine tenderloin tail.",
			secondFive.get(4).getTitle());

}
 
Example 13
Project: amv-access-api-poc   File: DemoServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public IssuerWithKeys getOrCreateDemoIssuer() {
    IssuerEntity demoIssuer = issuerRepository.findByName(DEMO_ISSUER_NAME, new PageRequest(0, 1))
            .getContent()
            .stream()
            .findFirst()
            .orElseGet(() -> this.createDemoIssuerWithKeys().getIssuer());

    String privateKeyBase64 = demoIssuer.getPrivateKeyBase64()
            .orElseThrow(IllegalArgumentException::new);

    return IssuerWithKeys.builder()
            .issuer(demoIssuer)
            .publicKey(KeyImpl.fromBase64(demoIssuer.getPublicKeyBase64()))
            .privateKey(KeyImpl.fromBase64(privateKeyBase64))
            .build();
}
 
Example 14
Project: spring-data-examples   File: SimpleUserRepositoryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void useSliceToLoadContent() {

	repository.deleteAll();

	// int repository with some values that can be ordered
	int totalNumberUsers = 11;
	List<User> source = new ArrayList<User>(totalNumberUsers);

	for (int i = 1; i <= totalNumberUsers; i++) {

		User user = new User();
		user.setLastname(this.user.getLastname());
		user.setUsername(user.getLastname() + "-" + String.format("%03d", i));
		source.add(user);
	}

	repository.save(source);

	Slice<User> users = repository.findByLastnameOrderByUsernameAsc(this.user.getLastname(), new PageRequest(1, 5));

	assertThat(users, contains(source.subList(5, 10).toArray()));
}
 
Example 15
Project: poppynotes   File: NoteServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFindArchivedNotesByUserIdPaginated_withCorrectUserIdFirstPage4Items_shouldReturnCorrectAndSorted() {
	List<OverviewNote> notes = service.findArchivedNotesByUserIdPaginated(1l, new PageRequest(0, 4));

	assertEquals("should return 4 notes", 4, notes.size());
	assertTrue("should contain first pinned entry", notes.get(0).getTitle().equals("a1-pinned-latest"));
	assertTrue("should contain second pinned entry", notes.get(1).getTitle().equals("a2-pinned-second"));
	assertTrue("should contain third pinned entry", notes.get(2).getTitle().equals("a3-pinned-third"));
	assertTrue("should contain first regular entry", notes.get(3).getTitle().equals("a1latest"));
	OverviewNote firstNote = notes.get(0);
	Note expectedFirst = archivedDao.findOne(firstNote.getId());

	assertEquals("check last edit", expectedFirst.getLastEdit(), firstNote.getLastEdit());
	assertEquals("check if part content is part of content",
			StringUtils.abbreviate(expectedFirst.getContent(), NotesServiceImpl.OVERVIEW_CONTENT_PART_LENGTH),
			firstNote.getPartContent());
	assertEquals("check title", expectedFirst.getTitle(), firstNote.getTitle());
	assertEquals("check pinned", expectedFirst.getPinned(), firstNote.getPinned());
}
 
Example 16
Project: bootstrap   File: PaginationJsonTest.java   Source Code and License 6 votes vote down vote up
/**
 * Sorted direction with ordering and corresponding ORM column.
 */
@Test
public void getPageRequestFullOrderingAlias() {
	// create a mock URI info with pagination informations
	final UriInfo uriInfo = newUriInfo();
	uriInfo.getQueryParameters().add(DataTableAttributes.PAGE_LENGTH, "100");
	uriInfo.getQueryParameters().add(DataTableAttributes.SORTED_COLUMN, "2");
	uriInfo.getQueryParameters().add("columns[2][data]", "col1");
	uriInfo.getQueryParameters().add(DataTableAttributes.SORT_DIRECTION, "asc");
	final Map<String, String> map = Collections.singletonMap("col1", "c.colOrm");
	final PageRequest pageRequest = paginationJson.getPageRequest(uriInfo, map);
	Assert.assertNotNull(pageRequest);
	Assert.assertNotNull(pageRequest.getSort());
	Assert.assertEquals(0, pageRequest.getOffset());
	Assert.assertEquals(0, pageRequest.getPageNumber());
	Assert.assertNull(pageRequest.getSort().getOrderFor("c.colOrm?"));
	Assert.assertNotNull(pageRequest.getSort().getOrderFor("UPPER(c.colOrm)"));
	Assert.assertEquals(Direction.ASC, pageRequest.getSort().getOrderFor("UPPER(c.colOrm)").getDirection());
	Assert.assertEquals(100, pageRequest.getPageSize());
}
 
Example 17
Project: pinkyLam-Blog-Server   File: ArticleController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("articleList")
public PageableResultJson articleList(@RequestParam(value = "page") Integer page, Long id, String title) {
	PageableResultJson tableJson = new PageableResultJson();
	Sort sort = new Sort(Direction.DESC, "id");
	Pageable pageable = new PageRequest(page, PageableResultJson.PAGE_SIZE, sort);
	Page<Article> pageData = null;
	if (StringUtils.isEmpty(title)) {
		pageData = articleDao.findArticleByAuthorId(id, pageable);
	} else {
		pageData = articleDao.findArticleByAuthorIdAndTitleLike(id, title, pageable);
	}

	tableJson.setData(pageData.getContent());
	tableJson.setPageSize(PageableResultJson.PAGE_SIZE);
	tableJson.setTotalPageNumber(pageData.getTotalPages());
	return tableJson;
}
 
Example 18
Project: springboot-learning-example   File: CityESServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<City> searchCity(Integer pageNumber,
                             Integer pageSize,
                             String searchContent) {
    // 分页参数
    Pageable pageable = new PageRequest(pageNumber, pageSize);

    // Function Score Query
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("cityname", searchContent)),
                ScoreFunctionBuilders.weightFactorFunction(1000))
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)),
                    ScoreFunctionBuilders.weightFactorFunction(100));

    // 创建搜索 DSL 查询
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withPageable(pageable)
            .withQuery(functionScoreQueryBuilder).build();

    LOGGER.info("\n searchCity(): searchContent [" + searchContent + "] \n DSL  = \n " + searchQuery.getQuery().toString());

    Page<City> searchPageResults = cityRepository.search(searchQuery);
    return searchPageResults.getContent();
}
 
Example 19
Project: springboot-learning-example   File: CityESServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 根据搜索词构造搜索查询语句
 *
 * 代码流程:
 *      - 权重分查询
 *      - 短语匹配
 *      - 设置权重分最小值
 *      - 设置分页参数
 *
 * @param pageNumber 当前页码
 * @param pageSize 每页大小
 * @param searchContent 搜索内容
 * @return
 */
private SearchQuery getCitySearchQuery(Integer pageNumber, Integer pageSize,String searchContent) {
    // 短语匹配到的搜索词,求和模式累加权重分
    // 权重分查询 https://www.elastic.co/guide/cn/elasticsearch/guide/current/function-score-query.html
    //   - 短语匹配 https://www.elastic.co/guide/cn/elasticsearch/guide/current/phrase-matching.html
    //   - 字段对应权重分设置,可以优化成 enum
    //   - 由于无相关性的分值默认为 1 ,设置权重分最小值为 10
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
            .add(QueryBuilders.matchPhraseQuery("name", searchContent),
            ScoreFunctionBuilders.weightFactorFunction(1000))
            .add(QueryBuilders.matchPhraseQuery("description", searchContent),
            ScoreFunctionBuilders.weightFactorFunction(500))
            .scoreMode(SCORE_MODE_SUM).setMinScore(MIN_SCORE);

    // 分页参数
    Pageable pageable = new PageRequest(pageNumber, pageSize);
    return new NativeSearchQueryBuilder()
            .withPageable(pageable)
            .withQuery(functionScoreQueryBuilder).build();
}
 
Example 20
Project: xm-ms-dashboard   File: PaginationUtilUnitTest.java   Source Code and License 6 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content,new PageRequest(6, 50),400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 21
Project: forweaver2.0   File: WeaverDao.java   Source Code and License 5 votes vote down vote up
/** 태그를 이용하여 위버를 검색함.
 * @param tags
 * @param page
 * @param size
 * @return 회원 목록
 */
public List<Weaver> getWeavers(List<String> tags, int page,int size) {
	Criteria criteria = new Criteria("tags").all(tags).and("isLeave").is(false);

	Query query = new Query(criteria);
	query.with(new PageRequest(page - 1, size));

	return mongoTemplate.find(query, Weaver.class);
}
 
Example 22
Project: apollo-custom   File: FavoriteServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
@Sql(scripts = "/sql/favorites/favorites.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testSearchByAppId() {
  List<Favorite> favorites = favoriteService.search(null, "test0621-04", new PageRequest(0, 10));
  Assert.assertEquals(3, favorites.size());
}
 
Example 23
Project: nixmash-blog   File: SimpleProductRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
public FacetPage<Product> findByFacetOnCategory(Pageable pageable) {

	FacetQuery query = new
			SimpleFacetQuery(new Criteria(IProduct.DOCTYPE_FIELD)
					.is(SolrDocType.PRODUCT));

	query.setFacetOptions(new FacetOptions(Product.CATEGORY_FIELD)
			.setPageable(new PageRequest(0,20)));

	return getSolrOperations().queryForFacetPage(query, Product.class);
}
 
Example 24
Project: xq_seckill_microservice   File: EstateController.java   Source Code and License 5 votes vote down vote up
@GetMapping("/estates/all/{page}")
public byte[] listAllByPage(@PathVariable("page") int page) {
    pageable = new PageRequest(page - 1, 100);
    List<EstateItemDTO> list = estateService.listAllByPage(pageable);
    if (CollectionUtils.isNotEmpty(list)) {
        return ProtoStuffUtil.serializeList(list);
    }
    return null;
}
 
Example 25
Project: apollo-custom   File: NamespaceServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testFindPublicAppNamespace() {

  AppNamespace publicAppNamespace = MockBeanFactory.mockAppNamespace(null, testPublicAppNamespace, true);
  when(appNamespaceService.findPublicNamespaceByName(testPublicAppNamespace)).thenReturn(publicAppNamespace);

  Namespace firstParentNamespace =
      MockBeanFactory.mockNamespace("app", ConfigConsts.CLUSTER_NAME_DEFAULT, testPublicAppNamespace);
  Namespace secondParentNamespace =
      MockBeanFactory.mockNamespace("app1", ConfigConsts.CLUSTER_NAME_DEFAULT, testPublicAppNamespace);
  Namespace childNamespace =
      MockBeanFactory.mockNamespace("app2", ConfigConsts.CLUSTER_NAME_DEFAULT, testPublicAppNamespace);


  Pageable page = new PageRequest(0, 10);

  when(namespaceRepository.findByNamespaceName(testPublicAppNamespace, page))
      .thenReturn(Arrays.asList(firstParentNamespace, secondParentNamespace));

  doReturn(false).when(namespaceService).isChildNamespace(firstParentNamespace);
  doReturn(false).when(namespaceService).isChildNamespace(secondParentNamespace);
  doReturn(true).when(namespaceService).isChildNamespace(childNamespace);

  List<Namespace> namespaces = namespaceService.findPublicAppNamespaceAllNamespaces(testPublicAppNamespace, page);

  assertEquals(2, namespaces.size());
}
 
Example 26
Project: ARCLib   File: SolrStore.java   Source Code and License 5 votes vote down vote up
/**
 * Counts all instances that respect the selected {@link Params}.
 *
 * <p>
 *     Though {@link Params} one could specify filtering. For further explanation
 *     see {@link Params}.
 * </p>
 *
 * @param params Parameters to comply with
 * @return Total number of instances
 */
default Long count(Params params) {
    SimpleQuery query = new SimpleQuery();
    query.addCriteria(typeCriteria());
    query.addSort(new Sort(new Sort.Order(Sort.Direction.valueOf(params.getOrder().toString()), params.getSort())));
    query.addProjectionOnField("id");
    query.setPageRequest(new PageRequest(params.getPage(), params.getPageSize()));
    query.addFilterQuery(new SimpleFilterQuery(buildFilters(params)));

    Page<U> page = getTemplate().query(query, getUType());
    return page.getTotalElements();
}
 
Example 27
Project: shoucang   File: NewPostsService.java   Source Code and License 5 votes vote down vote up
@Transactional(readOnly = true)
public void initNewPosts() {
    // Load all post ids from database to Redis
    PageRequest page = new PageRequest(0, Integer.MAX_VALUE, Sort.Direction.ASC, "id");
    Page<Post> posts = postRepository.findPublicPosts(page, PostStatus.PUBLIC);
    posts.forEach(post -> {
        this.add(post);
        this.addTaggedPost(post, tagRepository.findPostTags(post.getId()));
    });
}
 
Example 28
Project: Plum   File: ArticleServiceImpl.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 29
Project: bootstrap   File: PaginationJsonTest.java   Source Code and License 5 votes vote down vote up
/**
 * No sorted direction.
 */
@Test
public void getPageRequestSortedDirection() {
	// create a mock URI info with pagination informations
	final UriInfo uriInfo = newUriInfo();
	uriInfo.getQueryParameters().add(DataTableAttributes.PAGE_LENGTH, "100");
	uriInfo.getQueryParameters().add(DataTableAttributes.SORTED_COLUMN, "2");
	final PageRequest pageRequest = paginationJson.getPageRequest(uriInfo, null);
	Assert.assertNotNull(pageRequest);
	Assert.assertFalse(pageRequest.getSort().isSorted());
	Assert.assertEquals(0, pageRequest.getOffset());
}
 
Example 30
Project: shoucang   File: TagResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /admin/tags -> get all the tags.
 */
@RequestMapping(value = "/admin/tags",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<Tag>> getAllTags(Pageable pageable)
    throws URISyntaxException {
    Pageable pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), Sort.Direction.DESC, "id");
    Page<Tag> page = tagRepository.findAll(pageRequest);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/admin/tags");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 31
Project: banana   File: UserRepositoryTest.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 32
Project: spring-data-tarantool   File: PagingIntegrationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testPaging() {
    Page<User> userPage = pagingUserInterface.findAll(new PageRequest(0, 5));

    List<User> users = userPage.getContent();
    Assert.assertThat(users, hasSize(5));
    Assert.assertThat(
            users.stream().map(it -> it.id).collect(Collectors.toList()),
            contains(LongStream.rangeClosed(1, 5).boxed().toArray(Long[]::new))
    );
}
 
Example 33
Project: spring-backend-boilerplate   File: AuditReportRestSupportImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Page<AuditEventAggregation> listAuditReportByDay(String realm, PageQueryParameter queryRequest) {
	return auditEventAggregationRepository.findPageByRealmAndAggregationTypeOrderByAggregationKeyDesc(realm,
																									  AggregationType.DAY,
																									  new PageRequest(
																											  queryRequest
																													  .getStart(),
																											  queryRequest
																													  .getLimit()));
}
 
Example 34
Project: iotplatform   File: JpaDeviceDao.java   Source Code and License 5 votes vote down vote up
@Override
public List<Device> findDevicesByTenantId(UUID tenantId, TextPageLink pageLink) {
  return DaoUtil.convertDataList(
      deviceRepository.findByTenantId(fromTimeUUID(tenantId), Objects.toString(pageLink.getTextSearch(), ""),
          pageLink.getIdOffset() == null ? NULL_UUID_STR : fromTimeUUID(pageLink.getIdOffset()),
          new PageRequest(0, pageLink.getLimit())));
}
 
Example 35
Project: spring-backend-boilerplate   File: AuthReportRestSupportImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Page<AuthEventAggregation> listAuthReportByMonth(String realm, PageQueryParameter queryRequest) {
	return authEventAggregationRepository.findPageByRealmAndAggregationTypeOrderByAggregationKeyDesc(realm,
																									 AggregationType.MONTH,
																									 new PageRequest(
																											 queryRequest
																													 .getStart(),
																											 queryRequest
																													 .getLimit()));
}
 
Example 36
Project: role-api   File: SimpleUsersServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void findByCriteria_validPage_returnUsersPage() {
    final Pageable page = new PageRequest(0, 10);
    final Page<User> expectedUsers = new PageImpl<>(Arrays.asList(USER_1, USER_2));

    when(usersRepositoryMock.findAll(page)).thenReturn(expectedUsers);

    Page<User> users = usersService.findByCriteria(page);

    assertThat(users, equalTo(expectedUsers));
}
 
Example 37
Project: amv-access-api-poc   File: DemoServiceImpl.java   Source Code and License 5 votes vote down vote up
public ApplicationEntity getOrCreateDemoApplication() {
    return applicationRepository.findByName(DEMO_APP_NAME, new PageRequest(0, 1))
            .getContent()
            .stream()
            .findFirst()
            .orElseGet(this::createDemoApplication);
}
 
Example 38
Project: miaohu   File: QuestionServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public PageDTO findAllQuestion(int page) {
    Page<Question> list = questionRepository.findAll(new PageRequest(page,10,
            new Sort(Sort.Direction.DESC,"creationDate")));
    List<QuestionDTO> DTOs = new ArrayList<>();
    list.forEach(question -> DTOs.add(new QuestionDTO(question,questionVoteRepository.countAllByQuestion(question))));
    return new PageDTO(list,DTOs);
}
 
Example 39
Project: spring-backend-boilerplate   File: NewsRestSupportImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Page<NewsSummary> listNews(NewsQueryParameter queryRequest) {
	Page<News> newsPage = newsService.listNews(queryRequest);
	return new PageImpl<>(newsPage.getContent().stream().map(NewsSummary::from).collect(Collectors.toList()),
						  new PageRequest(queryRequest.getStart(), queryRequest.getLimit()),
						  newsPage.getTotalElements());
}
 
Example 40
Project: mall   File: AdminClassificationController.java   Source Code and License 5 votes vote down vote up
@RequestMapping("/list.do")
@ResponseBody
public ResultBean<List<Classification>> findAll(int type,
                                                int pageindex, @RequestParam(value = "pageSize", defaultValue = "15") int pageSize) {
    List<Classification> list = new ArrayList<>();
    if (pageindex == -1)
        list = classificationService.findAll(type);
    else {
        Pageable pageable = new PageRequest(pageindex, pageSize, null);
        list = classificationService.findAll(type, pageable).getContent();
    }
    return new ResultBean<>(list);
}
 
Example 41
Project: DiscussionPortal   File: DiscussionPortalDao.java   Source Code and License 5 votes vote down vote up
@Override
public Page<DbQuestion> getAllQuestions(int pageNo) {
	
	try {
		PageRequest request = new PageRequest(pageNo, SIZE+SIZE, Sort.Direction.DESC, "creationDate");
		return quesRepo.findAll(request);
	} catch(Exception ex) {
		throw new RuntimeException("Error while accessing all questions", ex);
	}
}
 
Example 42
Project: bootstrap   File: PaginationJsonTest.java   Source Code and License 5 votes vote down vote up
/**
 * No page display provided, mean all data
 */
@Test
public void getPageRequestNoPageSize() {
	// create a mock URI info with pagination informations
	PageRequest pageRequest = paginationJson.getPageRequest(newUriInfo(), null);
	Assert.assertNotNull(pageRequest);
	Assert.assertFalse(pageRequest.getSort().isSorted());
	Assert.assertEquals(0, pageRequest.getOffset());
	Assert.assertEquals(0, pageRequest.getPageNumber());
	Assert.assertEquals(10, pageRequest.getPageSize());
}
 
Example 43
Project: springboot_op   File: UserController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/curpage")
public List<UserEntity> curPage(int page){
	UserEntity user = new UserEntity();
	user.setSize(2);
	user.setPage(page);
	user.setSort("desc");
	Sort.Direction direction = Sort.Direction.DESC;
	Sort sort = new Sort(direction, "name");
	PageRequest pageRequest = new PageRequest(user.getPage() - 1, user.getSize(), sort);
	List<UserEntity> res = userService.curPage(pageRequest);
	return res;
}
 
Example 44
Project: apollo-custom   File: ReleaseService.java   Source Code and License 5 votes vote down vote up
@Transactional
public Release rollback(long releaseId, String operator) {
  Release release = findOne(releaseId);
  if (release == null) {
    throw new NotFoundException("release not found");
  }
  if (release.isAbandoned()) {
    throw new BadRequestException("release is not active");
  }

  String appId = release.getAppId();
  String clusterName = release.getClusterName();
  String namespaceName = release.getNamespaceName();

  PageRequest page = new PageRequest(0, 2);
  List<Release> twoLatestActiveReleases = findActiveReleases(appId, clusterName, namespaceName, page);
  if (twoLatestActiveReleases == null || twoLatestActiveReleases.size() < 2) {
    throw new BadRequestException(String.format(
        "Can't rollback namespace(appId=%s, clusterName=%s, namespaceName=%s) because there is only one active release",
        appId,
        clusterName,
        namespaceName));
  }

  release.setAbandoned(true);
  release.setDataChangeLastModifiedBy(operator);

  releaseRepository.save(release);

  releaseHistoryService.createReleaseHistory(appId, clusterName,
                                             namespaceName, clusterName, twoLatestActiveReleases.get(1).getId(),
                                             release.getId(), ReleaseOperation.ROLLBACK, null, operator);

  //publish child namespace if namespace has child
  rollbackChildNamespace(appId, clusterName, namespaceName, twoLatestActiveReleases, operator);

  return release;
}
 
Example 45
Project: sctalk   File: RecentSessionServiceController.java   Source Code and License 5 votes vote down vote up
/**
 * 查询最新会话
 * @param userId 用户ID
 * @param lastUpdateTime 最后更新时间
 * @return 会话列表
 * @since  1.0
 */
@GetMapping(path = "/recentSession")
public BaseModel<List<SessionEntity>> getRecentSession(@RequestParam("userId") long userId,
        @RequestParam("updateTime") int lastUpdateTime) {

    SearchCriteria<IMRecentSession> recentSessionCriteria = new SearchCriteria<>();
    recentSessionCriteria.add(JpaRestrictions.eq("userId", userId, false));
    recentSessionCriteria.add(JpaRestrictions.eq("status", 0, false));
    recentSessionCriteria.add(JpaRestrictions.gt("updated", lastUpdateTime, false));

    // 取最多100条
    Sort sort = new Sort(Sort.Direction.DESC, "updated");
    Pageable pageParam = new PageRequest(0, 100, sort);
    Page<IMRecentSession> recentSessions = recentSessionRepository.findAll(recentSessionCriteria, pageParam);

    BaseModel<List<SessionEntity>> sessionRes = new BaseModel<List<SessionEntity>>();

    List<SessionEntity> recentInfoList = new ArrayList<>();
    if (recentSessions.getSize() > 0) {
        recentSessions.forEach(recentSession -> {

            SessionEntity recentInfo = new SessionEntity();
            recentInfo.setId(recentSession.getId());
            recentInfo.setPeerId(recentSession.getPeerId());
            recentInfo.setPeerType(recentSession.getType());
            recentInfo.setTalkId(recentSession.getUserId());
            recentInfo.setLatestMsgType(recentSession.getType());
            recentInfo.setCreated(recentSession.getCreated());
            recentInfo.setUpdated(recentSession.getUpdated());
            recentInfoList.add(recentInfo);
        });
    }

    return sessionRes;
}
 
Example 46
Project: SpringBoot_Wechat_Sell   File: OrderMasterRepositoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void findByBuyerOpenid() throws Exception {
    PageRequest request = new PageRequest(1, 3);

    Page<OrderMaster> result = repository.findByBuyerOpenid(OPENID, request);

    Assert.assertNotEquals(0, result.getTotalElements());
}
 
Example 47
Project: gamesboard   File: RepositoryUserService.java   Source Code and License 5 votes vote down vote up
@Override
public List<User> search(String email, String sessionEmail) {
	Pageable pageRequest = new PageRequest(0, 10);
	User session = userRepository.searchUserByEmailWithCollections(sessionEmail);
	Set<Usr> notIn = new HashSet<Usr>(session.getUsr().getContacts());
	notIn.add(session.getUsr());
	Page<User> page = null;
	if (notIn == null || notIn.isEmpty()) {
		page = userRepository.findByEmailLike(email + "%", pageRequest);
	} else {
		page = userRepository.findByEmailLikeAndUsrIsNotIn(email + "%", notIn.isEmpty() ? null : notIn, pageRequest);
	}
	return page.getContent();
}
 
Example 48
Project: strqlbuilder   File: StrQLBuilderNativeTest.java   Source Code and License 5 votes vote down vote up
@Test
   public void pagedTest() {
StrQLBuilder sql = StrQLBuilder.createNative()
	.select("p.name")
	.from("Person p");
Pageable pageable = new PageRequest(0, 10);
PagedTypedQuery<String> query = sql.createPagedQuery(entityManager, String.class, pageable);
Page<String> persons = query.getResultList();
assertThat(persons, is(not(nullValue())));
assertThat(persons.getContent(), hasSize(2));
assertThat(persons.getNumberOfElements(), is(2));
assertThat(persons.getTotalElements(), is(2L));
   }
 
Example 49
Project: SpringBoot_Wechat_Sell   File: SellerOrderController.java   Source Code and License 5 votes vote down vote up
@GetMapping("/list")
public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size,
                         Map<String, Object> map) {

    PageRequest pageRequest = new PageRequest(page - 1, size);
    Page<OrderDTO> orderDTOPage = orderService.findListAll(pageRequest);
    map.put("orderDTOPage", orderDTOPage);
    map.put("currentPage", page);
    map.put("size", size);

    return new ModelAndView("order/list", map);

}
 
Example 50
Project: Food_Ordering_System   File: RunningInformationController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/findByTotalRunningTimeGreaterThan/{totalRunningTime}", method = RequestMethod.GET)
public ResponseEntity<?> findByTotalRunningTimeGreaterThan(@PathVariable double totalRunningTime,
                                                           @RequestParam(name = "page",defaultValue = defaultListAllPage) int page,
                                                           @RequestParam(name = "size",defaultValue = defaultListAllSize) int size)
{
    Sort order = new Sort(Sort.Direction.DESC, "totalRunningTime");
    List<RunningInformation> content = runningInformationService.findByTotalRunningTimeGreaterThan(totalRunningTime,
            new PageRequest(page,size,order)).getContent();
    return new ResponseEntity<List<JSONObject>>(getJsonResult(content),HttpStatus.OK);
}
 
Example 51
Project: nixmash-blog   File: PostServiceImpl.java   Source Code and License 5 votes vote down vote up
@Transactional(readOnly = true)
@Override
public Page<Post> getPublishedPostsByTagId(long tagId, int pageNumber, int pageSize) {
    PageRequest pageRequest =
            new PageRequest(pageNumber, pageSize, sortByPostDateDesc());
    return postRepository.findPagedPublishedByTagId(tagId, pageRequest);
}
 
Example 52
Project: pinkyLam-Blog-Server   File: FileController.java   Source Code and License 5 votes vote down vote up
@RequestMapping("attachList")
public PageableResultJson attachList(@RequestParam(value = "page") Integer page, Long userId) {
	PageableResultJson tableJson = new PageableResultJson();
	Sort sort = new Sort(Direction.DESC, "id");
	Pageable pageable = new PageRequest(page, 12, sort);
	Page<Attach> pageData = attachDao.findAttachByAuthorId(userId, pageable);
	tableJson.setData(pageData.getContent());
	tableJson.setPageSize(12);
	tableJson.setTotalPageNumber(pageData.getTotalPages());
	return tableJson;
}
 
Example 53
Project: spring-backend-boilerplate   File: NewsServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getImageFileObjectId(News news) {
	if (news == null) {
		return null;
	}
	Page<FileObject> fileObjects = fileObjectRepository.findByBizId(news.getId(), new PageRequest(0, 1));
	if (fileObjects.getContent() != null && !fileObjects.getContent().isEmpty()) {
		return fileObjects.getContent().get(0).getId();
	}
	return null;
}
 
Example 54
Project: unibave-backend   File: PageDTO.java   Source Code and License 5 votes vote down vote up
@JsonCreator
public PageDTO(@JsonProperty("content") List<T> content,
        @JsonProperty("number") int number,
        @JsonProperty("size") int size,
        @JsonProperty("totalElements") Long totalElements) {
    super(content, new PageRequest(number, size), totalElements);
}
 
Example 55
Project: apollo-custom   File: NamespaceServiceTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = BadRequestException.class)
public void testFindPublicAppNamespaceWithWrongNamespace() {
  Pageable page = new PageRequest(0, 10);

  when(appNamespaceService.findPublicNamespaceByName(testPublicAppNamespace)).thenReturn(null);

  namespaceService.findPublicAppNamespaceAllNamespaces(testPublicAppNamespace, page);
}
 
Example 56
Project: uckefu   File: UserController.java   Source Code and License 5 votes vote down vote up
@RequestMapping("/fans/list/{userid}")
@Menu(type = "apps" , subtype = "user" , access = true)
public ModelAndView fanslist(HttpServletRequest request , HttpServletResponse response, @PathVariable String userid) throws Exception {
	ModelAndView view = request(super.createAppsTempletResponse("/apps/user/fans")) ; 
	Pageable page = new PageRequest(super.getP(request), super.getPs(request), new Sort(Direction.DESC, "createtime")) ;
	Page<Fans> fansList = fansRes.findByUser(userid, page) ;
	
	List<String> userids = new ArrayList<String>();
	for(Fans fan : fansList){
		userids.add(fan.getCreater()) ;
	}
	if(userids.size()>0){
		view.addObject("fansList",new PageImpl<User>(userRes.findAll(userids), page, fansList.getTotalElements()) ) ;
	}
	
	User curruser = userRes.findById(userid) ;
	if(super.getUser(request).isLogin()){
		view.addObject("fan" , fansRes.findByUserAndCreater(userid , super.getUser(request).getId())) ;
	}
	view.addObject("curruser", curruser) ;
	
	view.addObject("follows", fansRes.countByCreater(userid)) ;
	
	view.addObject("fans", fansRes.countByUser(userid)) ;
	
    return view ;
}
 
Example 57
Project: bootstrap   File: PaginationJson.java   Source Code and License 5 votes vote down vote up
/**
 * Build the {@link PageRequest} with ordering information.
 */
private PageRequest buildOrderedPageRequest(final Map<String, String> ormMapping, final MultivaluedMap<String, String> parameters,
		final int pageLength, final int firstPage, final Collection<String> caseSensitiveColumns) {
	return Optional.ofNullable(getSortColumn(parameters))
			.map(c -> newSortedPageRequest(ormMapping, parameters, pageLength, firstPage, c, caseSensitiveColumns))
			.orElse(PageRequest.of(firstPage, pageLength));
}
 
Example 58
Project: IPPR2016   File: ProcessModelStorageController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "processes", method = RequestMethod.GET)
public @ResponseBody Callable<List<ProcessModelDTO>> getAllProcesses(
    final HttpServletRequest request,
    @RequestParam(value = "page", required = true) final int page,
    @RequestParam(value = "size", required = false, defaultValue = "10") final int size) {
  return () -> {
    final PageRequest pageRequest =
        new PageRequest(page, size, new Sort(Sort.Direction.ASC, "name"));

    return processModelService.findActiveProcessModels(pageRequest).get();
  };
}
 
Example 59
Project: nixmash-blog   File: SimpleProductRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
public FacetPage<Product> findByFacetOnAvailable(Pageable pageable) {
	FacetQuery query = new SimpleFacetQuery(new
					Criteria(IProduct.DOCTYPE_FIELD).is(SolrDocType.PRODUCT));
	query.setFacetOptions(new FacetOptions(Product.AVAILABLE_FIELD).setFacetLimit(5));
	query.setPageRequest(new PageRequest(0, 100));
	return getSolrOperations().queryForFacetPage(query, Product.class);

}
 
Example 60
Project: BLOG-Microservice   File: UserServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Page<User> findUserByPageAndOrder(Integer starPage, Integer itemNumber) {
    List<Sort.Order> orders = new ArrayList<>();
    // orders.add(new Sort.Order(Sort.Direction.DESC,"name"));
    orders.add(new Sort.Order(Sort.Direction.DESC,"id"));
    //  orders.add(new Sort.Order(Sort.Direction.ASC,"parentId"));
    PageRequest pageRequest = new PageRequest(starPage,itemNumber,new Sort(orders));
    return userRepository.findAll(pageRequest);
}