Docs

Add a Paginated Grid

Learn how to populate a grid with paginated data from an application service.

Paginated data refers to datasets that are too large to fit in memory, even after filtering. Instead, the data is loaded in chunks (pages) from an application service as needed. Both filtering and sorting are delegated to the service layer (typically a database).

In Vaadin, the Grid component has built-in support for paginated data (often referred to as lazy loading in API documentation). When the user scrolls or changes the sorting/filtering criteria, the grid requests the appropriate data page from the backend service. To the user, this appears as a seamless scrolling experience.

This guide starts with a complete example that you can copy-paste into your project if you want. It then breaks down the example into sections that explain how to populate, filter, and sort the grid. The guide does not cover setting up the Grid component itself; for that, see the Grid component documentation.

Copy-Paste into Your Project

If you want to quickly try out a paginated grid in your application, copy-paste the following code into your project:

Source code
PaginatedGridView.java

For more detailed walk-through of the example code, continue reading below.

Getting the Data

The Grid component can request pages either by using a page number and size, or by using an offset and limit. If the dataset is sorted, you have to sort it before applying pagination.

This example uses offset-based pagination. The application service defines its own ItemSortOrder record for the sorting information, so that its API doesn’t depend on Vaadin’s data provider classes:

Source code
PaginatedGridView.java

In a real world application, the service would be in its own file and the data would be queried from a database.

Populating the Grid

You populate the grid with paginated data by passing it a callback function that fetches data pages on demand. The callback function receives a Query object that contains information about the requested page, sorting, and filtering criteria.

Source code
PaginatedGridView.java

Spring Data Support

If you are using Spring Data, use the setItemsPageable() method. It passes a Spring Data Pageable object to the callback function, so you don’t have to convert the page and sorting information yourself. The application service can pass it on to a Spring Data repository:

Source code
Java
// Spring Data repository:
interface ItemRepository extends JpaRepository<Item, Long> {
    List<Item> findByNameContainingIgnoreCase(String name, Pageable pageable);
}

// Application service:
@Service
@Transactional(readOnly = true)
@PreAuthorize("isAuthenticated()")
public class ItemService {

    private final ItemRepository repository;

    ItemService(ItemRepository repository) {
        this.repository = repository;
    }

    public List<Item> findItems(String filterString, Pageable pageable) {
        return repository.findByNameContainingIgnoreCase(filterString, pageable);
    }
}

// In the view class:
grid.setItemsPageable(pageable -> service
    .findItems(filterField.getValue(), pageable)
);

Unlike Vaadin’s data provider classes, Pageable doesn’t tie the API of the service to the user interface, so the service can accept it directly.

Note
Can the View Call the Repository Directly?
Yes, for a simple, read-only grid, if the access control of the view is enough and no business logic is involved. Otherwise, call an application service, as in the example above. See Calling Repositories from Views for details.

Filtering

The filtering happens in the application service and the filter string is passed to the service via the callback function. Because of this, you have to refresh the grid whenever the filter string changes:

Source code
PaginatedGridView.java

Sorting

Sorting happens in the application service and the sort orders are passed to the service via the callback function. Only columns with a specific sort property are sortable:

Source code
PaginatedGridView.java

Sort properties are strings that are passed to the application service. They typically correspond to database column names, but in this example they are mapped to the record fields in the Item class.

The grid describes the requested sort orders as Vaadin QuerySortOrder objects. The view converts them into ItemSortOrder records before calling the service:

Source code
PaginatedGridView.java

Handling Errors

The callback function runs whenever the grid needs more data, so a failing service call, such as a database timeout, can happen at any time while the user scrolls. If the exception isn’t caught, it ends up in the application’s error handler, and the user doesn’t get any feedback about the rows that failed to load.

Catch the exception in the callback, tell the user what happened, and return an empty result. If the failing page isn’t the first one, the grid assumes it scrolled past the end of the data and requests the earlier pages again, until it reaches the start of the data and ends up empty. Remember that the load failed, so that these repeated calls neither query the failing service again nor open another notification, and clear the flag whenever the data provider is refreshed, for example when the filter changes. Refreshing the data provider resets the grid and loads the data again, so you can offer that as a retry action:

Source code
Java
private boolean loadFailed;

// In the constructor:
grid.setItems(query -> {
    if (loadFailed) {
        return Stream.empty();
    }
    try {
        return service.findItems(
                query.getOffset(),
                query.getLimit(),
                toItemSortOrders(query.getSortOrders()),
                filterField.getValue())
            .stream();
    } catch (DataAccessException e) {
        log.error("Error loading items", e);
        loadFailed = true;
        showLoadError(grid);
        return Stream.empty();
    }
});
grid.getDataProvider().addDataProviderListener(event -> loadFailed = false);

private void showLoadError(Grid<?> grid) {
    var notification = new Notification();
    notification.addThemeVariants(NotificationVariant.ERROR);
    var retryButton = new Button("Retry", event -> {
        notification.close();
        grid.getDataProvider().refreshAll();
    });
    notification.add(new Span("Loading the data failed."), retryButton);
    notification.setDuration(0);
    notification.open();
}

Don’t return placeholder items to fill the requested page, as they appear as real rows and can be selected or edited. If you also pass a count callback to setItems(), handle errors in it in the same way, for example by returning 0.

Updated –