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.
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 displaypageSize
: This is the number of data items to load on the pagesortField
: 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 valueThe 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.
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.
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
.