0
votes

I have a backend application made in spring boot, and I want to load in front end, comments about some topic, and I load these comments paginated and sorted, it works fine if user just scrolls, and get the next page, but there is a problem, users can post comments as well, and these comments go in the table, from which we get paginated comments to send to front end. The problem is that if I get two pages for example with 10 comments each, and then post a comment that will go let's say somewhere between elements of the first page, because comments are sorted, then all items after the inserted comment are shifted by one position, and so the first comment of the third page will be the last element of the second page that was already sent to front end, and I get duplicate comments.

Pageable pageable = PageRequest.of(page, 8, Sort.by("text").ascending());

List<Comment> commentsPage = commentsRepository.findAllByBookId(bookId, pageable);

@Repository 
public interface CommentsRepository extends JpaRepository<Comment, String> {
    List<Comment> findAllByBookId(String bookId, Pageable pageable);
}

To solve this I was thinking of memorizing in the front end how many comments are added, and when I ask the next page to specify them to skip that number of comments, but I don't know how to do that.

I'm new to java and spring boot, if there are other solutions how I could solve this I'm open to suggestions.

1
Sorting by time would be an easy solution. New comments always go onto the end. Is there a reason you're sorting by text?Michael
The usual way to solve this problem is to use a "continuation token" instead of an offset. Basically you specify the ID of the last item you got, instead of using page numbers. Not sure if Spring supports it. phauer.com/2017/web-api-pagination-continuation-tokenMichael
You could also change your findAll method to take a timestamp. It would then effectively become a "findAllBefore". The UI would specify the time on the initial request, and would make sure to send the same timestamp on subsequent page requests. Any items added since the page load would then be filtered by JPA's WHERE clause.Michael
@Michael, I sorted them by text just to check if pagination works with sorting, but yes, comments must be sorted by time. But if I only do that, all new comments will be stored at the end, but when I get there with pagination what should I do? It will return the comments added at beginning as last page let's say, and these comments are already in front end.Raul1998

1 Answers

0
votes

U can use @CreationTimestamp to find out the time at which any comment is created and then sort it in ascending order

@CreationTimestamp
 private LocalDateTime createdAt;

Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by("createdAt").ascending());