获取有关Spring Data数据的最后记录

Dav*_*cía 27 java spring spring-mvc spring-data

我正在尝试在Spring Data存储库中定义一个方法来获取按日期排序的表上的最后记录.这是我的实体:

@Entity
public class News {

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String text;

    private Date publicationDate;

    /* Getters and Setters */
}
Run Code Online (Sandbox Code Playgroud)

这是我的存储库:

public interface NewsRepository extends JpaRepository<News, Long> {
    List<News> findFirst5OrderByPublicationDateDesc();
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用启动项目,我会收到下一个错误:

引起:org.springframework.data.mapping.PropertyReferenceException:找不到类型Date的属性desc!遍历路径:News.publicationDate.

如果我删除了Desc,我会得到这个:

引起:java.util.NoSuchElementException

我做错了什么?

Dav*_*cía 52

事实证明该方法的签名是不正确的.正确的是:

findFirst5ByOrderByPublicationDateDesc()
Run Code Online (Sandbox Code Playgroud)

有点混乱,因为在官方样本中他们有这个:

List<User> findTop10ByLastname(String lastname, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,那里只有一个,通常的那个.

  • 有没有办法在这样的查询中也引入 和 id ?例如:`findFirstByOrderByPublicationDateDescAndId(String id)` (6认同)

小智 12

Spring JPaRepository具有分页功能,可以提供很大的帮助.这也将完美地运作

要返回前10条记录,您可以使用:

创建自定义Pageable对象

Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "id");

Page<News> topPage = newsRepository.findByPublicationDate(id, pageable);
List<News> topUsersList = topPage.getContent();
Run Code Online (Sandbox Code Playgroud)

在NewsRepository接口中,请务必创建一个方法

 Page<News> findByPublicationDate(Date date, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)

这将返回最高记录.

要返回最后10条记录,您可以使用:

Pageable pageable = new PageRequest(0, 10, Sort.Direction.DESC, "id");

Page<News> bottomPage = newsRepository.findByPublicationDate(id, pageable);
// this is a list of the last 10 records, you can choose to invert it by using
List<News> bottomUsersList = bottomPage.getContent();

Collections.inverse(bottomUsersList);
Run Code Online (Sandbox Code Playgroud)

这将重用相同的NewsRespoitory,因此无需在那里创建另一个方法.

使用页面的优点是可以灵活地按另一列进行排序.(ASC或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");
Run Code Online (Sandbox Code Playgroud)

10可以替换为您需要返回的任何数量的记录

  • 这很好用,但请注意只读的 Collections.reverse(MYLIST)。您应该复制该列表,然后将其反转。`List&lt;News&gt; reversedNews = new ArrayList&lt;&gt;(bottomPage.getContent()); Collections.reverse(reversedNews);` (2认同)