Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination in Google App Engine with Java

I need to create simple pagination of objects, but when I read manual I found out that query.setRange(5, 10); will fetch 10 objects, even when only 5 objects are needed.

Is there anyway to fetch just needed objects?

EDIT: I started bounty, so fi you can show me simple example code in Java that works, then I will accept you answer.

like image 824
newbie Avatar asked Jun 10 '10 18:06

newbie


3 Answers

How about this:

List<Employee> results = (List<Employee>) query.execute();
// Use the first 20 results...

Cursor cursor = JPACursorHelper.getCursor(results);
String cursorString = cursor.toWebSafeString();
// Store the cursorString...

// ...

// Query query = the same query that produced the cursor
// String cursorString = the string from storage
Cursor cursor = Cursor.fromWebSafeString(cursorString);
query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
query.setRange(0, 20);

List<Employee> results = (List<Employee>) query.execute();
// Use the next 20 results...

From:

How to use datastore cursors with jpa on GAE

Also:

http://groups.google.com/group/google-appengine-java/browse_thread/thread/5223215ff24c3b3e/d22297d1d76a9c8b

Or without JPA see:

http://code.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/Cursor.html

like image 84
Pablojim Avatar answered Oct 15 '22 19:10

Pablojim


There's an article about this very topic on the App Engine site:

http://code.google.com/appengine/articles/paging.html

The examples are in Python, but they're simple enough that you can probably translate to Java fairly easily.

Here's a Java implementation, which I have not read or tested.

like image 24
ʇsәɹoɈ Avatar answered Oct 15 '22 19:10

ʇsәɹoɈ


Why is it a problem if 10 objects are returned from the database? You will still be returned just the 5 objects that you care about (the first 5 are discarded).

I'm not asking because I think the setRange method is a solution that scales incredibly well, but it is a simple and reasonable solution that is more than adequate in a good number of cases.

Are you planning on paging extremely large tables or incorporate expensive joins? If not, I'd be tempted to use setRange as the starting point for your pagination.

like image 1
Jeff Avatar answered Oct 15 '22 20:10

Jeff