Skip to content

Instantly share code, notes, and snippets.

Last active May 5, 2020 07:04
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Eager Fetching With Result Limiting
public interface UserRepository extends JpaRepository<User, Long> {
@EntityGraph(attributePaths = {"messages"})
List<User> findTop5By();
// JPQL does not support LIMIT
// We need to use Pageable to set the number of ids we want
@Query("SELECT id " +
"FROM User ")
List<Long> findIds(Pageable pageable);
@EntityGraph(attributePaths = {"messages"})
List<User> findByIdIn(List<Long> userIds);
void fetch5UsersWithMessages() {
// ❌Does the limiting in memory
// Triggers HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!
List<User> users = findTop5By();
// ✅Does the limiting in SQL
// Get 5 user ids with JPQL and Pageable
List<Long> userIds = findIds(PageRequest.of(0, 5));
// Get the users and messages associated to the ids
List<User> usersFromIds = findByIdIn(userIds);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment