如何在 Spring Data JPA 中获取 countQuery 返回的计数?

How to get count returned by countQuery in Spring Data JPA?

我在 Repository 图层中同时使用 nativeQuerycountQuery 作为:

@Query(value = "select * FROM Person p where p.forename = :forename and p.surname = :surname",
countQuery = "SELECT count(*) FROM Person p where p.forename = :forename",
  nativeQuery = true)
User findByForenameAndSurname(@Param("surname") String lastname,
                             @Param("forename") String firstname);
}

我想要此 countQuery 返回的整数计数,我想使用该计数来构造 PageRequest 对象,我想将其用于 nativeQuery 以获取 Page 目的。我可以在构造 PageRequest 对象之前访问这个计数吗? 有没有办法得到countQuery?

返回的值

如果您需要该页面,那么只需 return 它:

@Query(value = "select * FROM Person p where p.forename = :forename and p.surname = :surname",
      countQuery = "SELECT count(*) FROM Person p where p.forename = :forename",
      nativeQuery = true)
Page<User> findByForenameAndSurname(@Param("surname") String lastname,
                             @Param("forename") String firstname);
}

Page 对象将包含您需要的所有内容。