Get last records ordered by date on Spring Data

后端 未结 2 1544
暖寄归人
暖寄归人 2020-12-28 13:40

I\'m trying to define a method in a Spring Data repository to fetch the last records on a table ordered by date. This is my entity:

@Entity
public class News         


        
2条回答
  •  萌比男神i
    2020-12-28 14:04

    Spring JPaRepository has pagination which can be of great help. This will also work perfectly

    To return the top 10 records, you can use:

    Create a custom Pageable object

    Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "id");
    
    Page topPage = newsRepository.findByPublicationDate(id, pageable);
    List topUsersList = topPage.getContent();
    

    In the NewsRepository interface, be sure to create a method

     Page findByPublicationDate(Date date, Pageable pageable);
    

    This will return the top records.

    To return the last 10 records, you can use:

    Pageable pageable = new PageRequest(0, 10, Sort.Direction.DESC, "id");
    
    Page bottomPage = newsRepository.findByPublicationDate(id, pageable);
    // this is a list of the last 10 records, you can choose to invert it by using
    List bottomUsersList = bottomPage.getContent();
    
    Collections.inverse(bottomUsersList);
    

    This will reuse the same NewsRespoitory, so no need to create another method there.

    The advantage of using pages is that it becomes flexible to sort by another column. (Either ASC or DESC)

    // To get top by text
    Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "text");
    // Top by title
    Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "title");
    // Top by publicationDate
    Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "publicationDate");
    

    10 can be replaced by whatever number of records you need returned

提交回复
热议问题