SpringData paging with PageImpl the size does not work

0

I created a method inside a service class to generate a paged product list 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 paginated list:

Ifyounoticetheattributesaysthiswiththevalue24,soyoucanbringthe4elementsofthelistbecauseitisthetotalthatIhaveregistered,butifIchangethisattributesize,thelistofitemsshouldcomewiththequantityequivalentifthevalueassignedislessthanIhaveregisteredproducts:

Asyoucansee,IplacedthesizeparameterintheURI,thepageableobjectreceivedandrecognizedthesizeparametercorrectly,butitdidnothaveeffectintheproductlist,withtheparameterinthevalue1shouldreturnonly1itemandnotthetotalquantity.IbelieveIamnotabletoworkwiththePageImpl<>inthecorrectway,howtocorrectthissituation?Hereisthecodeforthemethodoftheresourceclassresponsibleforcallingtheservicemethod:

@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);
    }
    
asked by anonymous 20.10.2018 / 06:13

2 answers

0

In order to get the result I needed, I ended up changing the query approach, before I was doing the query creating a keyword statement inside the repository, but when I converted this list to another format I could not take the pageable, pageable manually on the new created list, this was the problem.

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

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

The 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 product list that was generated by the already paged getResultList (), then I convert it so that its elements have the structure of my DTO.

    
04.11.2018 / 18:57
0

I believe the problem is in the database query. As you are setting up the page I believe that the registry control should be yours, spring will not make it automatic.

Test by getting 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 does not work, I think you have to do the control manually.

    
25.10.2018 / 16:08