Spring PagingAndSortingRepository delete entry during processing

Viewed 815

Im using spring PagingAndSortingRepository to do pagination of database entries. During processing i need to delete some entries..

when i call the repository to delete, the entry is deleted, after that the problem is with the next pageable. i'm not getting the size number of elements from the next Pageable (pageRequest.next();).

Is there any way to iterate with pagination and perform in parallel crud operation.

Part of the code


 while (!onePage.isEmpty()) {
                while (pageIterator.hasNext()) {
                    Object nextElement = pageIterator.next();
                    if (!falseCondition) {
                        log.info("sending message with Id {}", nextElement.getId());
                        repository.deleteById(nextElement.getId());

                    } else {
                        log.info("Lost connection");
                        return;
                    }
                }

                pageRequest = pageRequest.next();
                onePage = repository.findAll(pageRequest);
                pageIterator = onePage.iterator();

            }

Many thanks.

1 Answers

Like @ruba pointed out in the example, it is not a hibernate issue. Even if you using jdbc API directly you will have to handle the situation. I can propose you a solution

  • You can implement your custom spring-data-jpa repository method where the service pass the pageRequest but you translate it to offset and limit. So instead of calling pageRequest.next() you do the following which takes into account of the items deleted.
        long nextPageNumber = pageRequest.getPageNumber() + 1;
        long nextOffset = nextPageNumber * pageRequest.getPageSize() 
                          - itemsDeletedInCurrentPage;
        long limit = pageRequest.getPageSize();
        
        List<Item> itemsInNextPage = em.createQuery(query)
                .setFirstResult(offset)
                .setMaxResults(limit)
                .getResultList();
Related