Hibernate Select Top and Bottom n Rows with Criteria

前端 未结 7 1984
孤街浪徒
孤街浪徒 2021-02-07 00:33

Let\'s say I have two tables, Books and Reviews. Reviews has a column, stars, that can have a value between 1 and 5. A Book can have many Reviews.

How would I select al

7条回答
  •  天涯浪人
    2021-02-07 00:55

    Two HQL queries using org.springframework.data.domain.Pageable like:

    before in the middle-layer-service you create pageable and call repo:

    Pageable pageableTop = new PageRequest(0, 3, Direction.ASC, "yourFieldToSortBy");
    yourRepository.findTopOrderByYourEntity(pageableTop);
    
    Pageable pageableBottom = new PageRequest(0, 3, Direction.DESC, "yourFieldToSortBy");
    yourRepository.findTopOrderByYourEntity(pageableBottom);
    

    the repo:

    public interface YourRepository extends CrudRepository {
    
        @Query("FROM YourEntity")
        List findTopOrderByYourEntity(Pageable pageable);
    }
    

提交回复
热议问题