4

after querying from the database using the given getAll(Pageable pageable) method from spring data jpa i become an Page object. What I am doing is modifing the content list inside of this Page object but I am getting stuck here is that I dont know how to set it back to the Page object because Page doesn't have setter method, something like page.setContent(newContent), it has only getter.

Can anyone give me some hints how to set the new content to the Page object without changing the other current properties inside of it?

Ock
  • 1,262
  • 3
  • 18
  • 38
  • 2
    There is no way, you must construct new Page instance (`org.springframework.data.domain.PageImpl`) based on Page obtained from `getAll` call. Question is why do you even need to modify the original page? – Nikolai Shevchenko May 16 '19 at 08:33
  • The same case as me.--- > Question is why do you even need to modify the original page?--- Repo method returns a collection of entities, but I what to pass to user thier representation. Suppose, I don't want to pass `user.password` or `user.email` for the users list request. – Vijit Oct 23 '20 at 20:19

2 Answers2

4

You need to use PageImpl(List content, Pageable pageable, long total) as example below :

//get paged data 
Page<Groups> groups = groupsRepository.
                    findPagedGroups(pageable, lowerCase(name), lowerCase(description));

// update list
List<Groups> groupsList = groups.stream().collect(Collectors.toList());
for (Groups group : groupsList) {
   group.setSize(usersGroupsRepository.countActiveUsersGroupsForGroupId(group.getId()));
}

// return new PageImpl
return new PageImpl<>(groupsList, pageable, groups.getTotalElements());
Tomasz
  • 884
  • 8
  • 12
0

Page's map method returns a new Page with the content of the current one mapped by the given converter function.

public Page<User> findAllMasked(Pageable pageable) {
    Page<User> users = repo.findAll(pageable);
    return users.map(user -> {
        user.setPassword("***");
        return user;
    });
}
István Békési
  • 993
  • 4
  • 16
  • 27