Handling tons of data – LazyDataModel

The dataTable component provides support for displaying tons of data by enabling lazy loading. In order to handle large datasets, a data model needs to be implemented based on org.primefaces.model.LazyDataModel to support pagination, sorting, filtering, and live scrolling.

How to do it…

First, the lazy attribute should be set to true for lazy loading to be enabled for the table, and the abstract load method should be implemented in org.primefaces.model.LazyDataModel. We must also implement the getRowData and getRowKey methods when selection is enabled in the table. The lazy data model should be constructed with the list of Car instances and be bound to the table:

List<Car> cars = new ArrayList<Car>(millions_of_cars);
LazyDataModel<Car>lazyModel = new LazyCarDataModel(cars);

The table calls the load method implementation with the following parameters when paging, sorting, or filtering actions occur:

  • first: This is the index of the first data to display
  • pageSize: This is the number of data items to load on the page
  • sortField: This is the name of the sort field (for example, "name" for sortBy="#{car.name}")
  • sortOrder: This is the org.primefaces.model.SortOrder enumeration; the value could be either ASCENDING, DESCENDING, or UNSORTED
  • filter: This filters the map with a field name as the key (for example, "name" for filterBy="#{car.name}") and the value

The total row count should also be set to the lazy data model in order to get the pagination work done properly by invoking the setRowCount method of the data model.

There's more…

The field attribute is provided by <p:column>; this is where the name of the field is passed to the load method in the sortField or filter method arguments according to the action taken. If field is not provided, the name of the field will be extracted from the values of the filterBy or sortBy attributes.

Note

Integrating JPA's Criteria API with LazyDataModel is a good approach to generalize the sorting and filtering features of every table.

PrimeFaces Cookbook Showcase application

This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on application servers compatible with Servlet 3.x, such as JBoss WildFly and Apache TomEE.

The showcase for the recipe is available at http://localhost:8080/pf-cookbook/views/chapter5/dataTableLazyDataModel.jsf.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.126