【问题标题】:Get last records ordered by date on Spring Data获取 Spring Data 上按日期排序的最后记录
【发布时间】:2015-02-18 11:11:38
【问题描述】:

我正在尝试在 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 */
}

这是我的存储库:

public interface NewsRepository extends JpaRepository<News, Long> {
    List<News> findFirst5OrderByPublicationDateDesc();
}

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

原因: org.springframework.data.mapping.PropertyReferenceException:否 找到类型日期的属性描述!遍历路径:News.publicationDate。

如果我删除 Desc,我会得到:

原因:java.util.NoSuchElementException

我做错了什么?

【问题讨论】:

    标签: java spring spring-mvc spring-data


    【解决方案1】:

    原来方法的签名不正确。正确的是:

    findFirst5ByOrderByPublicationDateDesc()
    

    有点令人困惑,因为在官方示例中他们有这个:

    List<User> findTop10ByLastname(String lastname, Pageable pageable);
    

    如您所见,那里只有一个,通常的那个。

    【讨论】:

    • 有没有办法在这样的查询中也引入和标识?例如:findFirstByOrderByPublicationDateDescAndId(String id)
    • @TatianaB,是的! findFirstByIdOrderByPublicationDateDesc(String id)
    【解决方案2】:

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

    在NewsRepository接口中,一定要创建方法

     Page<News> findByPublicationDate(Date date, Pageable pageable);
    

    这将返回最高记录。

    要返回最后 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);
    

    这将重用相同的 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");
    

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

    【讨论】:

    • 这很好用,但要注意 Collections.reverse(MYLIST) 是只读的。您应该复制该列表,然后将其反转。 List&lt;News&gt; reversedNews = new ArrayList&lt;&gt;(bottomPage.getContent()); Collections.reverse(reversedNews);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多