Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.