Springdata paging with Pageimpl<> size does not work

Asked

Viewed 1,287 times

0

I created a method within a service class to generate a paged list of products using Springdata (Java Spring Rest application), follow the code:

public Page<ProdutoDTOVendedor> listarProdutos(String descricao, Boolean disponivel,
            Integer page, Integer size, String orderBy, String direction) {

        //Rotina para validação do usuário do end-point
        UserSS us = AuthService.authenticated();

        Optional<Vendedor> vendedor = vendedorRepository.findById(us.getId());
        if (!vendedor.isPresent()) {
            throw new ObjectNotFoundException("Vendedor não encontrado");
        }

        Pageable pageable = PageRequest.of(page, size, Direction.valueOf(direction), orderBy);

        List<ProdutoDTOVendedor> produtosVendedor = new ArrayList<>();

        Optional<List<ItemVendedor>> itensVendedor = itemVendedorRepository.findByIdVendedorEqualsAndIdProdutoDescricaoDetalhadaContaining(vendedor.get(), descricao);
        for (ItemVendedor item : itensVendedor.get()) {
            produtosVendedor.add(itemVendedorToProdutoDTOVendedor(item));
        }
        Page<ProdutoDTOVendedor> produtosPage = new PageImpl<ProdutoDTOVendedor>(produtosVendedor,pageable,  (pageable.getOffset() + pageable.getPageSize()));      
        return produtosPage;
    }

The method generates the following paged list:

inserir a descrição da imagem aqui

If you understand the attribute says this with the value 24, so it can bring the 4 elements of the list because it is the total that I have registered, but if I change this attribute size, the list of items should come with the equivalent amount if the assigned value is less than I have of registered products:

inserir a descrição da imagem aqui As you can see I put in the URI the size parameter, the pageable object received and recognized the size parameter correctly, but it did not have an effect in the product list, with the parameter in the value 1 should return only 1 item and not the total quantity. I believe that I am not able to work with Pageimpl<> in the correct way, how to correct this situation? Below follows the method code of the Resource class responsible for calling the service method:

@GetMapping(value="/produtos/list")
    public ResponseEntity<Page<ProdutoDTOVendedor>> listarProdutos(

            @RequestParam(value = "descricao", defaultValue = "") String descricao,
            @RequestParam(value = "disponivel", defaultValue = "") Boolean disponivel,
            @RequestParam(value = "page", defaultValue = "0") Integer page,
            @RequestParam(value = "size", defaultValue = "24") Integer size,
            @RequestParam(value = "orderBy", defaultValue = "descricao") String orderBy,
            @RequestParam(value = "direction", defaultValue = "ASC") String direction) {
        Page<ProdutoDTOVendedor>  produtos = vendedorService.listarProdutos(descricao, disponivel, page, size, orderBy, direction);
        return ResponseEntity.ok().body(produtos);
    }

2 answers

0


to achieve the result that needed I ended up changing the approach of the query, before I was performing the query by creating a keyword statement within the Repository, but when I converted this list to another format I could not avail the pageable, nor implement a pageable manually in the new created list, this was the problem.

Therefore, I decided to create the query in the service itself using Entitymanager and JPQL, the querys created through this approach that return lists support that you work with paging, for this you just indicate the setFirstResult and the setMaxResults so with this information your list may be paginated. Let’s go to the code regarding the application of the consultation (I simplified the consultation to facilitate the understanding), this consultation was within the service search method:

String instrucao = "select prod from Produto prod order by descricaoDetalhada ";

Query jpql = em.createQuery(instrucao);

jpql.setFirstResult((page-1) * size); 
jpql.setMaxResults(size);

@SuppressWarnings("unchecked")
List<Produto> produtos = jpql.getResultList();

Page and size variables continue to come from within the method signature:

public List<ProdutoDTOList> listarProdutosParaVincular(String descricao, Long categoriaID, Integer page, Integer size) 

Having the list of products that was generated by getResultList() already paged, then I convert it so that its elements have the structure of my DTO.

0

I believe the problem lies in the database query. As you are mounting the page I believe the registration control should be yours, spring will not make it automatic.

Take a test by receiving a Pageable element in the get method and use findAll to see if it works

Ex

public ResponseEntity<Page<ProdutoDTOVendedor>> pesquisar(Pageable pageable) {
    // ...
    return itemVendedorRepository.findAll(pageable)
}

Running try to pass the pageable in your search method

itemVendedorRepository.findByIdVendedorEqualsAndIdProdutoDescricaoDetalhadaContaining

If it doesn’t work I believe you have to do the manual control.

  • 1

    Marcelo talks, okay? Due to the time of the question, I changed the consultation approach to be able to work with pagination in this scenario. Before as I had described, using an approach through the keyword method (Keywords) in the Pository, so I switched to an approach using the Entitymanager and JPQL query in the service itself. I’ll put in the answer to what I did, but anyway thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.