Skip to content

Instantly share code, notes, and snippets.

@yannbriancon
Last active May 5, 2020 07:04
Show Gist options
  • Save yannbriancon/09630296a21639ea2d271e9ddc8503fd to your computer and use it in GitHub Desktop.
Save yannbriancon/09630296a21639ea2d271e9ddc8503fd to your computer and use it in GitHub Desktop.
Eager Fetching With Result Limiting
@Repository
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