Change page size of Pageable(spring boot jpa) - spring-boot

I´m working showing some info on a table and I´m using #PageableDefault(size = Constants.PAGE_SIZE) Pageable pageable to determine the size of the page im showing(5 elements at the moment).
The point here is that I want to be able to change the value of that page size using a <select> to be able to modify the page size in my controller and redirect it into my table endpoint:
#PostMapping("/size")
public String size(){
//Constants.PAGE_SIZE;
return "redirect:/users/showusers";
}
Any help will be appreciated.

You can pass page request like this, pass your size variable in page request.
PageRequest pageRequest = PageRequest.of(0, 5); //or default
use below to pass page size dynamically..
PageRequest pageRequest = PageRequest.of(0, size);
in repository method pass Pageable pageable

Related

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

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?
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());

how to pass value dynamically to spring top function

Actually, I wanted to retrieve the Top 500 records in a table. I knew spring data has internal method findTop500 method for it. My question is can this 500 be passed dynamically? Suppose if my requirement changes to get Top1000 I don't want it to modify again.
Assuming you are asking about Spring data-methods
You can use a Pageable object to dynamically set how many entries you want to retrieve.
You can use it like this:
PageRequest pageRequest = new PageRequest(0, maxResults);
List<Record> records = repository.findAll(pageRequest);
List<Record> records = repository.findAllByKey(key, pageRequest);

How to get top results using specifications in spring data jpa?

I am quite new to spring data jpa. I am trying to use specifications while querying database. My question is using crudrepository we can method like :
findTopByUsernameOrderByUpdatedAtDesc(String username);
How can I achieve the same using specifications? I can do basic things like and or in specifications, but not very robust like we can do with criteria etc.
Specification<CustomClass> spec = Specifications.where(specification).and(username);
List<CustomClass> list = findAll(spec);
This was done as follows :
Pageable pageable = new PageRequest(0, 1, Sort.Direction.DESC, "username");
Page oneElementPage = repository.findAll(spec, pageable);
This will sort the data on username column in descending direction and return first result.
You can't express this in a Specification directly. But you can use a Pageable for this:
Page oneElementPage = repository.findAll(spec, new PageRequest(0, 1));
Gives you a Page with a single element.

Spring dynamically select #JsonView with pagination

I want to select the Json View applied to my data depending on an URL parameter. I am trying to implement this using #JsonView annotations, and I tried some solutions (1, 2). The thing is that those solutions are basen on the controller action returning a MappingJacksonValue, but I cannot use that because I am using pagination.
My action:
public ResponseEntity<Page<MyEntity>> findAll(
int viewMode,
Pageable pageable) {
result = service.findAll(pageable);
// Here I would like to apply a Json View to the result set depending
// on the variable viewMode
return new ResponseEntity<Page<MyEntity>>(
/* Resultset with the selected view applied, and paginated */,
HttpStatus.OK
);
}
To make #JsonView work with pagination, you need to set the following property to true in application.properties:
spring.jackson.mapper.DEFAULT_VIEW_INCLUSION = true
This will cause the mapper to also serialize properties which are not annotated, enabling paging to work.

Primefaces dataTable issues

What is the method to refresh data on subsequent pages - second page, third page, etc - of a Primefaces dataTable using the LazyDataModel method?
Also, if I select an item in a dataTable to view its detail on another page, then came back to the dataTable using either the browser's Back button or implement JavaScript's history.back() method, it seems that the dataTable always reset its position to the first page instead of going back to the page the user was on. How can I force the dataTable to stay on the last viewed page?
My codes for lazy loading are:
private final class LazyLoader extends LazyDataModel<BookModel>
{
private static final long serialVersionUID = 1L;
public LazyLoader(String sort, String category, String operator, String input) {
setListing(getBookService().getListing(sort, category, operator, input));
}
#Override
public List<BookModel> load(int first, int pageSize, String sortField, boolean sortOrder, Map<String, String> filters) {
return getListing();
}
}
And for the Submit method is:
public String Submit()
{
sort = sortBean.getSort();
category = categoryBean.getCategory();
operator = operatorBean.getOperator();
input = searchBean.getInput();
lazyModel = new LazyLoader(sort, category, operator, input);
lazyModel.setRowCount(listing.size());
return null;
}
I'm using #ViewScoped for listing the book records as well as showing detail of a book record.
Does anyone has similar issues with Primefaces dataTable?
Keep using #ViewScoped. You should not use #SessionScoped unless you have real needs for it.
To remember the last page, you have to set the first attribute of the load method. You can do that with request parameters. Something like: yourview.xhtml?f=3 .
About the refreshing, the thing is that you are using a lazy loader but you're loading everything at once... Your load method is the one that should do the query on demand, that is, page by page.
Does pagination work for you without lazy loading? I would verify that works as expected before you jump into the hardest case.
If you want your dataTable to remember the last pagination after you navigate away from the JSF page then you need to make your managed bean SessionScoped. The lifecycle of the ViewScoped managed bean ends after navigation leaves the view.
In order to keep the selected page you have to do 2 things.
First make the managedBean session scoped.
Second set a binding between the datatable and a UIData object. In your backend bean for example put
private UIData filasUIData = null;
public UIData getFilasUIData() {
return filasUIData;
}
public void setFilasUIData(UIData filasUIData) {
this.filasUIData = filasUIData;
}
Now in your data table
<ice:dataTable
binding="#{yourBean.filasUIData}"
that´s all.

Resources