Last active
May 5, 2020 07:04
-
-
Save yannbriancon/09630296a21639ea2d271e9ddc8503fd to your computer and use it in GitHub Desktop.
Eager Fetching With Result Limiting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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