有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JPA查询方法:findTopX,其中X是给定的(变量)数?

我正在创建一个RESTful API。我需要能够向API发送一个数字,指定它需要返回的新闻项的数量

我已经寻找了一些东西,根据documentation可以限制你的结果,但是我找不到任何关于如何使它变为变量的东西。所以我的问题是:这是否可能,或者我是否需要为此编写自己的自定义查询

我已经试过这样的方法: Iterable<NewsItem> findTopAmountByOrderByDatetimeDesc(Integer amount);其中Amount将由给定的整数“Amount”填充,但即使认为这是可能的,也可能是愚蠢的,尽管在我看来这是一个很好的特性

我现在拥有的(不是变量,所以它不关心给定的数字):

NewsItemApi:

@RequestMapping(value = "/newsitems/amount",
        produces = { "application/json" }, 
        method = RequestMethod.GET)

NewsItemRepository:

Iterable<NewsItem> findTop2ByOrderByDatetimeDesc();

NewsItemApicController:

public ResponseEntity<Iterable> getLastNewsItems(@NotNull @ApiParam(value = "amount of news items to return", required = true) @Valid @RequestParam(value = "amount", required = true) Integer amount) {
        return ResponseEntity.accepted().body(this.newsItemRepository.findTop2ByOrderByDatetimeDesc());
    }

共 (2) 个答案

  1. # 1 楼答案

    您可以创建存储库并使用@Query annotation进行自定义请求,如下所示:

    public interface NewsRepository extends JpaRepository<News, Long> {
    
      @Query(value = "SELECT * FROM NEWS ODER BY FIELD_YOU_WANT_TO_ODER_BY DESC LIMIT ?1", nativeQuery = true)
      List<News> getLatestNews(Integer amount);
    }
    
  2. # 2 楼答案

    您必须使用@Query,类似于:

    @Query("select n from NewsItem n order by n.datetime desc limit :num", nativeQuery = true)
    Iterable<NewsItem> findTopXByOrderByDatetimeDesc(@Param("num") int num);
    

    当然,根据您的数据库使用limit关键字