Java Code Examples for org.springframework.data.domain.Page#forEach()

The following examples show how to use org.springframework.data.domain.Page#forEach() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JpaSystemManagement.java    From hawkbit with Eclipse Public License 1.0 7 votes vote down vote up
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
// Exception squid:S2229 - calling findTenants without transaction is
// intended in this case
@SuppressWarnings("squid:S2229")
public void forEachTenant(final Consumer<String> consumer) {

    Page<String> tenants;
    Pageable query = PageRequest.of(0, MAX_TENANTS_QUERY);
    do {
        tenants = findTenants(query);
        tenants.forEach(tenant -> tenantAware.runAsTenant(tenant, () -> {
            try {
                consumer.accept(tenant);
            } catch (final RuntimeException ex) {
                LOGGER.debug("Exception on forEachTenant execution for tenant {}. Continue with next tenant.",
                        tenant, ex);
                LOGGER.error("Exception on forEachTenant execution for tenant {} with error message [{}]. "
                        + "Continue with next tenant.", tenant, ex.getMessage());
            }
            return null;
        }));
    } while ((query = tenants.nextPageable()) != Pageable.unpaged());

}
 
Example 2
Source File: TaskListQueryProcessor.java    From nacos-sync with Apache License 2.0 7 votes vote down vote up
@Override
public void process(TaskListQueryRequest taskListQueryRequest,
                    TaskListQueryResult taskListQueryResult, Object... others) {

    Page<TaskDO> taskDOPage;

    if (StringUtils.isNotBlank(taskListQueryRequest.getServiceName())) {

        QueryCondition queryCondition = new QueryCondition();
        queryCondition.setServiceName(taskListQueryRequest.getServiceName());
        taskDOPage = taskAccessService.findPageCriteria(taskListQueryRequest.getPageNum() - 1,
                taskListQueryRequest.getPageSize(), queryCondition);
    } else {

        taskDOPage = taskAccessService.findPageNoCriteria(taskListQueryRequest.getPageNum() - 1,
                taskListQueryRequest.getPageSize());

    }

    List<TaskModel> taskList = new ArrayList<>();

    taskDOPage.forEach(taskDO -> {
        TaskModel taskModel = new TaskModel();
        taskModel.setTaskId(taskDO.getTaskId());
        taskModel.setDestClusterId(taskDO.getDestClusterId());
        taskModel.setSourceClusterId(taskDO.getSourceClusterId());
        taskModel.setServiceName(taskDO.getServiceName());
        taskModel.setGroupName(taskDO.getGroupName());
        taskModel.setTaskStatus(taskDO.getTaskStatus());
        taskList.add(taskModel);
    });

    taskListQueryResult.setTaskModels(taskList);
    taskListQueryResult.setTotalPage(taskDOPage.getTotalPages());
    taskListQueryResult.setTotalSize(taskDOPage.getTotalElements());
    taskListQueryResult.setCurrentSize(taskList.size());
}
 
Example 3
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 自定义高级查询
 */
@Test
public void customAdvanceSelect() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本的分词条件
    queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
    // 排序条件
    queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
    // 分页条件
    queryBuilder.withPageable(PageRequest.of(0, 2));
    Page<Person> people = repo.search(queryBuilder.build());
    log.info("【people】总条数 = {}", people.getTotalElements());
    log.info("【people】总页数 = {}", people.getTotalPages());
    people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge()));
}
 
Example 4
Source File: UsersController.java    From expper with GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/u/{username}", method = RequestMethod.GET)
public String show(@PathVariable String username, Model model) {
    User user = userRepository.findByLogin(username);

    if (user == null) {
        throw new PageNotFoundException("User " + username + " is not found.");
    }

    Page<Post> posts = postRepository.findUserPostsByStatus(user.getId(), PostStatus.PUBLIC, new PageRequest(0, 20));

    List<Long> ids = new ArrayList<>();
    posts.forEach(post -> ids.add(post.getId()));

    model.addAttribute("user", user);
    model.addAttribute("posts", posts);
    model.addAttribute("votes", new HashMap<Long, Vote>());
    model.addAttribute("counting", countingService.getPostListCounting(ids));

    return "users/show";
}
 
Example 5
Source File: SpringDataQueryTest.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 排序
 */
@Test
public void searchAndSort() {
    // 构建查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本分词查询
    queryBuilder.withQuery(QueryBuilders.termQuery("category", "手机"));
    // 排序
    queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
    // 搜索,获取结果
    Page<Item> items = itemRepository.search(queryBuilder.build());
    // 总条数
    long total = items.getTotalElements();
    System.out.println("总条数 = " + total);
    items.forEach(System.out::println);
}
 
Example 6
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 自定义高级查询
 */
@Test
public void customAdvanceSelect() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本的分词条件
    queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
    // 排序条件
    queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
    // 分页条件
    queryBuilder.withPageable(PageRequest.of(0, 2));
    Page<Person> people = repo.search(queryBuilder.build());
    log.info("【people】总条数 = {}", people.getTotalElements());
    log.info("【people】总页数 = {}", people.getTotalPages());
    people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge()));
}
 
Example 7
Source File: AbstractArticleServiceImpl.java    From Fame with MIT License 6 votes vote down vote up
@Override
public Page<ARTICLE> pageAdminArticle(Integer page, Integer limit, ArticleQuery articleQuery) {
    Page<ARTICLE> result = articleRepository.findAll((Specification<ARTICLE>) (root, query, criteriaBuilder) -> {
        List<Predicate> predicates = new ArrayList<>();

        predicates.add(criteriaBuilder.notEqual(root.get("status"), ArticleStatus.DELETE));
        if (!StringUtils.isEmpty(articleQuery.getStatus())) {
            predicates.add(criteriaBuilder.equal(root.get("status"), articleQuery.getStatus()));
        }
        if (!StringUtils.isEmpty(articleQuery.getTitle())) {
            predicates.add(criteriaBuilder.like(root.get("title"), "%" + articleQuery.getTitle() + "%"));
        }

        if (null != articleQuery.getPriority()) {
            predicates.add(criteriaBuilder.equal(root.get("priority"), articleQuery.getPriority()));
        }

        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    }, PageRequest.of(page, limit, FameUtil.sortDescById()));
    //只需要文章列表,不需要内容
    result.forEach(article -> article.setContent(""));
    return result;
}
 
Example 8
Source File: ApiTagsService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 查询标签全部列表
 * @return IPage<Tags>
 */
public List<Tags> findTagsByCondition(Tags tags, Pageable pageable) {
	Page<Tags> tagsQueryResults = tagsDao.findAll(pageable);
	tagsQueryResults.forEach(
			tag->tag.setTagsCount(Long.valueOf(tag.getArticles().size()))
	);
	return tagsQueryResults.getContent();
}
 
Example 9
Source File: CommentServiceImpl.java    From Fame with MIT License 5 votes vote down vote up
@Override
public Page<Comment> pageAdminComments(Integer page, Integer limit) {
    Comment record = new Comment();
    record.setStatus(CommentStatus.NORMAL);
    Page<Comment> result = commentRepository.findAll(Example.of(record), PageRequest.of(page, limit, FameUtil.sortDescById()));
    result.forEach(comments -> {
        String content = FameUtil.contentTransform(comments.getContent(), false, false, null);
        comments.setContent(content);
    });

    return result;
}
 
Example 10
Source File: CommentServiceImpl.java    From Fame with MIT License 5 votes vote down vote up
@Override
@Cacheable(value = COMMENT_CACHE_NAME, key = "'article_comments['+#page+':'+#limit+':'+#articleId+']'")
public Page<Comment> getCommentsByArticleId(Integer page, Integer limit, Integer articleId) {
    Comment record = new Comment();
    record.setArticleId(articleId);
    record.setStatus(CommentStatus.NORMAL);
    Page<Comment> result = commentRepository.findAll(Example.of(record), PageRequest.of(page, limit, FameUtil.sortDescById()));

    result.forEach(comments -> {
        String content = FameUtil.contentTransform(comments.getContent(), false, true, null);
        comments.setContent(content);
    });

    return result;
}
 
Example 11
Source File: BaseCommentServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Deprecated
public <T extends BaseCommentDTO> Page<T> filterIpAddress(Page<T> commentPage) {
    Assert.notNull(commentPage, "Comment page must not be null");
    commentPage.forEach(this::filterIpAddress);

    return commentPage;
}
 
Example 12
Source File: ConverterDtv.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public <U> Response<Page<U>> map(Page<T> info, Function<? super T, ? extends U> converter) {
    List<U> listU = new LinkedList<>();
    info.forEach((o) -> {
        U u = converter.apply(o);
        listU.add(u);
    });
    Page<U> result = new PageImpl<>(listU, info.getPageable(), info.getTotalElements());
    BeanUtils.copyProperties(info, result);
    return new Response<>(result);
}
 
Example 13
Source File: HotPostService.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
@Transactional(readOnly = true)
public void initHotPosts() {
    PageRequest page = new PageRequest(0, Integer.MAX_VALUE, Sort.Direction.DESC, "id");
    Page<Post> posts = postRepository.findPublicPosts(page, PostStatus.PUBLIC);
    posts.forEach(post -> {
        this.addHotPost(post);
        this.addTaggedPost(post, tagRepository.findPostTags(post.getId()));
    });
}
 
Example 14
Source File: ApiTagsService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 查询标签全部列表
 * @return IPage<Tags>
 */
public List<Tags> findTagsByCondition(Tags tags, Pageable pageable) {
	Page<Tags> tagsQueryResults = tagsDao.findAll(pageable);
	tagsQueryResults.forEach(
			tag->tag.setTagsCount(Long.valueOf(tag.getArticles().size()))
	);
	return tagsQueryResults.getContent();
}
 
Example 15
Source File: SpringDataQueryTest.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * rangeQuery:范围匹配
 */
@Test
public void testRangeQuery() {
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    queryBuilder.withQuery(QueryBuilders.rangeQuery("price").from(3000).to(4000));

    Page<Item> items = itemRepository.search(queryBuilder.build());
    items.forEach(System.out::println);
}
 
Example 16
Source File: NewPostsService.java    From expper with GNU General Public License v3.0 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 17
Source File: SpringDataQueryTest.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * TermQuery:词条匹配,不分词
 *
 * term是将传入的文本原封不动地(不分词)拿去查询。
 * match会对输入进行分词处理后再去查询,部分命中的结果也会按照评分由高到低显示出来。
 * match_phrase是按短语查询,只有存在这个短语的文档才会被显示出来。
 */
@Test
public void testTermQuery() {
    // 查询条件生成器
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    // term是将传入的文本原封不动地(不分词)拿去查询。
    builder.withQuery(QueryBuilders.termQuery("brand", "小米"));
    // 查询 自动分页 ,默认查找第一页的10条数据
    Page<Item> items = this.itemRepository.search(builder.build());
    items.forEach(System.out::println);
}
 
Example 18
Source File: SpringDataQueryTest.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * matchQuery:词条匹配,先分词然后在调用termQuery进行匹配
 */
@Test
public void matchQuery() {
    // 构建查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // match会对输入进行分词处理后再去查询,部分命中的结果也会按照评分由高到低显示出来。
    queryBuilder.withQuery(QueryBuilders.matchQuery("title", "坚果R1"));
    // 搜索,获取结果
    Page<Item> items = itemRepository.search(queryBuilder.build());
    // 总条数
    long total = items.getTotalElements();
    System.out.println("total = " + total);
    items.forEach(System.out::println);
}
 
Example 19
Source File: JpaRolloutManagement.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
private void createAssignmentOfTargetsToGroup(final Page<Target> targets, final RolloutGroup group) {
    targets.forEach(target -> rolloutTargetGroupRepository.save(new RolloutTargetGroup(group, target)));
}
 
Example 20
Source File: Application.java    From code-examples with MIT License 4 votes vote down vote up
@Bean
public CommandLineRunner specificationsDemo(MovieRepository movieRepository) {
    return args -> {

        // create new movies
        movieRepository.saveAll(Arrays.asList(
                new Movie("Troy", "Drama", 7.2, 196, 2004),
                new Movie("The Godfather", "Crime", 9.2, 178, 1972),
                new Movie("Invictus", "Sport", 7.3, 135, 2009),
                new Movie("Black Panther", "Action", 7.3, 135, 2018),
                new Movie("Joker", "Drama", 8.9, 122, 2018),
                new Movie("Iron Man", "Action", 8.9, 126, 2008)
        ));

        // search movies by `genre`
        MovieSpecification msGenre = new MovieSpecification();
        msGenre.add(new SearchCriteria("genre", "Action", SearchOperation.EQUAL));
        List<Movie> msGenreList = movieRepository.findAll(msGenre);
        msGenreList.forEach(System.out::println);

        // search movies by `title` and `rating` > 7
        MovieSpecification msTitleRating = new MovieSpecification();
        msTitleRating.add(new SearchCriteria("title", "black", SearchOperation.MATCH));
        msTitleRating.add(new SearchCriteria("rating", 7, SearchOperation.GREATER_THAN));
        List<Movie> msTitleRatingList = movieRepository.findAll(msTitleRating);
        msTitleRatingList.forEach(System.out::println);

        // search movies by release year < 2010 and rating > 8
        MovieSpecification msYearRating = new MovieSpecification();
        msYearRating.add(new SearchCriteria("releaseYear", 2010, SearchOperation.LESS_THAN));
        msYearRating.add(new SearchCriteria("rating", 8, SearchOperation.GREATER_THAN));
        List<Movie> msYearRatingList = movieRepository.findAll(msYearRating);
        msYearRatingList.forEach(System.out::println);

        // search movies by watch time >= 150 and sort by `title`
        MovieSpecification msWatchTime = new MovieSpecification();
        msWatchTime.add(new SearchCriteria("watchTime", 150, SearchOperation.GREATER_THAN_EQUAL));
        List<Movie> msWatchTimeList = movieRepository.findAll(msWatchTime, Sort.by("title"));
        msWatchTimeList.forEach(System.out::println);

        // search movies by title <> 'white' and paginate results
        MovieSpecification msTitle = new MovieSpecification();
        msTitle.add(new SearchCriteria("title", "white", SearchOperation.NOT_EQUAL));

        Pageable pageable = PageRequest.of(0, 3, Sort.by("releaseYear").descending());
        Page<Movie> msTitleList = movieRepository.findAll(msTitle, pageable);

        msTitleList.forEach(System.out::println);
    };
}