首页 > 解决方案 > 将结果限制为 1

问题描述

我有这个 Spring JPA 存储库:

@Repository
public interface MerchantUserRepository extends JpaRepository<Users, Integer> {

    Optional<Users> findByIdAndTypeIn(Integer id, String... types);
}

有没有办法将返回的行数限制为 1?

标签: javaspringspring-data-jpaspring-datasingle-page-application

解决方案


您将 Pageable 参数添加到查询中:

Optional<Users> findByIdAndTypeIn(Integer id, String... types, Pageable page);

对于一个结果,您可以像这样创建它:

Pageable firstRow = PageRequest.of(0, 1);

在这种情况下,您也可以考虑为您的查询添加一个Sort对象


推荐阅读