Home > Software design >  How to get count returned by countQuery in Spring Data JPA?
How to get count returned by countQuery in Spring Data JPA?

Time:12-16

I am using both nativeQuery and countQuery in my Repository layer as:

@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);
}

I want integer count returned by this countQuery and I want to use that count to construct PageRequest object which I want to use for nativeQuery to get the Page object. Can I access this count before constructing PageRequest object? Is there any way to get the value returned by countQuery?

CodePudding user response:

If you need the page then simply return it:

@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);
}

The Page object will contain all you need.

  • Related