Java – is there a portable way to have “select first 10 * from t” semantics?
I want to read the data in 10K record blocks from the database
I found result limits on Wikipedia. It seems obvious that this can't be done in a portable way
Another method might be the jdbctemplate, which provides many methods for queries, but how do I make sure enough rows have been read Through callbacks like rowmapper and resultsetextractor, it cannot be instructed to read enough data
Editor: I'm looking for a solution for the jdbctemplate. This post suggests using setmaxrows, which I ignored
Solution
Grab hibernate or JPA Both are familiar with various database dialects and will handle annoying DB details under the hood transparently
In Hibernate, you can use criteria #setfirstresult() and criteria #setmaxresults() for paging
List users = session.createCriteria(User.class) .addOrder(Order.asc("id")) .setFirstResult(0) // Index of first row to be retrieved. .setMaxResults(10) // Amount of rows to be retrieved. .list();
In JPA, you can use query#setfirstresult() and query#setmaxresults() for similar operations
List users = em.createQuery("SELECT u FROM User u ORDER BY u.id"); .setFirstResult(0) // Index of first row to be retrieved. .setMaxResults(10) // Amount of rows to be retrieved. .getResultList();