How to update the content inside of Page object from Spring Data without changing the other properties

5.7k views Asked by At

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?

2

There are 2 answers

1
Tomasz On

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());
0
István Békési On

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;
    });
}