I'm trying to implement pagination in my GAE queries and this is what I've come to:
public JSONArray getDeviceListByTypeWithCursor(String cursorString) {
PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
Query q = pm.newQuery(MobileDevice.class);
q.setRange(0, 100);
if(cursorString != "" && cursorString != null){
Cursor cursor;
try{
cursor = Cursor.fromWebSafeString(cursorString);
Map<String, Object> extensionMap = HashMap<String, Object>();
extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
q.setExtensions(extensionMap);
}catch(Exception e){
cursor = null;
}
}
JSONArray array = new JSONArray();
List<MobileDevice> results = (List<MobileDevice>) q.execute();
for (MobileDevice device : results) {
array.put(device.toJSON());
}
Cursor cursor = JDOCursorHelper.getCursor(results);
cursorString = cursor.toWebSafeString();
array.put(cursorString);
return array;
}
When I send a null cursorString I get the first 100 results + the new cursor as expected. However, when I send another request using the new cursor I get the correct results (#101-#200) but the same cursor string.
The datastore has a lot of entities (more than 100000), so this probably isn't due to end of results.
UPDATE
I've come to realize this might be due to problems with the Spring framework. We're using Spring 4.2.3 - but I don't see anything online regarding working with Spring and GAE, let alone Spring+GAE+Cursors..
So I've added a results.size()
call after executing the query (I also removed the loop iterating over the results) and that seemed to solve the problem for me. Hope this helps someone else down the road!