Let’s say there is a entity class like this
@Entity
public class User {
...
public Collection<User> followers;
...
}
Lets say user has thousands of user followers. I wanna paginate… Do I have to get my hands into JPQL to paginate the result without any other choice?
int page = 5;
User u = em.find(User.class, id);
for (User u : u.getFollowers(page, 100)) { // get the 5th 100 result
// do some stuff
}
is there any similar solution or a pattern out there? is it possible to paginate field of a collection runtime by just accessing a field u.getFollowers(page, 100) without the code below?
I know this one already…
int page = 5;
List<User> followers = em.createQuery("select u.followers from User u where u.id=?1", User.class)
.setParameter(1, id).setFirstResult(page*100).setMaxResult(100).getResultList();
which JPA implementation are you using?
if you are using hibernate you can take advantage of some of hibernates features.
as stated in the hibernate documentation
The
createFilter()method can be used to efficiently retrieve subsets of a collection without needing to initialize the whole collection.You can use
createFilter()to get the size of a collection without initializing it, also important for pagination.