Objectify paging with Cursors

前端 未结 2 1216
面向向阳花
面向向阳花 2021-01-04 21:11

I have this method in my RPC service:

@Override
    public Entrata[] getEntrate(int from, int to) {
        List data = entrateDao.list();
            


        
2条回答
  •  既然无缘
    2021-01-04 21:55

    I just want make sure you don't have any errors in your code since you can copy and past the Igor Artamonov code. Here is a cleaner code from Objectify Wiki with less errors and some documentation:

    // create the query and set the limit to 1000
    Query query = ofy().load().type(Car.class).limit(1000);
    
    // Here you get the cursor (if exists) from the request
    // For the first request, i-e the first page, this parameter(cursor) will be null
    String cursorStr = request.getParameter("cursor");
    
    // Here you check if cursor is not null and not empty
    // If so, we start our query from the last check point
    if (cursorStr != null && !cursorStr.isEmpty())
        query = query.startAt(Cursor.fromWebSafeString(cursorStr));
    
    // We need this variable to know when we have been loaded all the entries
    boolean remaining = false;
    QueryResultIterator iterator = query.iterator();
    while (iterator.hasNext()) {
        Car car = iterator.next();
    
        ... // your code here
    
        // We have found entries, so we set this variable to true.
        // That means, we have probably another page to fetch
        remaining = true;
    }
    
    // If we have found entries, we send the last check point
    if (remaining) {
        // we take the last check point by calling "toWebSafeString()" from the iterator's cursor
        Cursor cursor = iterator.getCursor();
        Queue queue = QueueFactory.getDefaultQueue();
        queue.add(url("/pathToThisServlet").param("cursor", cursor.toWebSafeString()));
    }
    

提交回复
热议问题