PrimeFaces DataTable Lazy Loading With Paging and Sorting
Use PrimeFaces DataTable lazy loading with LazyDataModel: paging, sorting and filtering pushed to the database through a repository query.

A table with 200,000 rows cannot be loaded into memory for every user, and a JSF view that tries will exhaust the heap long before the browser notices. PrimeFaces DataTable has a lazy mode that fetches only the page on screen, and asks your code for the rest when the user pages, sorts or filters. This guide applies to PrimeFaces 14 and later on Jakarta Faces 4, and it covers the page, the model, the safe translation of sort and filter input, and the traps that make a lazy table slower than the eager one.
The page
<h:form>
<p:dataTable var="o" value="#{orderList.model}" lazy="true"
paginator="true" rows="20" rowsPerPageTemplate="20,50,100"
sortBy="#{o.createdAt}" sortOrder="descending"
id="orders">
<p:column headerText="Id" sortBy="#{o.id}"><h:outputText value="#{o.id}" /></p:column>
<p:column headerText="Customer" sortBy="#{o.customer}" filterBy="#{o.customer}">
<h:outputText value="#{o.customer}" />
</p:column>
<p:column headerText="Created" sortBy="#{o.createdAt}">
<h:outputText value="#{o.createdAt}">
<f:convertDateTime type="localDateTime" pattern="yyyy-MM-dd HH:mm" />
</h:outputText>
</p:column>
</p:dataTable>
</h:form>lazy="true" tells the table not to hold a full list. The value is a LazyDataModel, not a collection. Each paging click, header sort or filter keystroke is an AJAX request that ends in a call to the model with the new page offset, sort order and filter values. The initial sortBy and sortOrder give the first load a defined order, which matters more than it looks: a query without an order returns rows in whatever order the database likes, and the pages can overlap.
The model
@Named
@ViewScoped
public class OrderList implements Serializable {
@Inject OrderRepository orders;
private LazyDataModel<Order> model;
@PostConstruct
void init() {
model = new LazyDataModel<>() {
@Override
public int count(Map<String, FilterMeta> filters) {
return (int) orders.count(toCriteria(filters));
}
@Override
public List<Order> load(int first, int pageSize,
Map<String, SortMeta> sort, Map<String, FilterMeta> filters) {
return orders.page(toCriteria(filters), toSort(sort), first, pageSize);
}
@Override
public String getRowKey(Order o) { return String.valueOf(o.getId()); }
@Override
public Order getRowData(String key) { return orders.find(Long.parseLong(key)); }
};
}
public LazyDataModel<Order> getModel() { return model; }
}count returns the total number of rows that match the current filters, so the paginator can draw page numbers. load must return exactly pageSize rows starting at first, or fewer on the last page. getRowKey and getRowData let the table keep a selection across pages, because it stores only keys. Older PrimeFaces versions set the row count inside load instead of overriding count, so check the method signatures against your version before copying this.
Translating sort and filter input safely
The sort field names and filter values arrive from the browser. Treat them as untrusted, and map them through a fixed list before they reach a query.
private static final Map<String, String> SORTABLE = Map.of(
"id", "o.id", "customer", "o.customer", "createdAt", "o.createdAt");
private Sort toSort(Map<String, SortMeta> sort) {
Sort result = Sort.unsorted();
for (SortMeta meta : sort.values()) {
String column = SORTABLE.get(meta.getField());
if (column == null) continue; // ignore unknown fields
result = result.and(Sort.by(meta.getOrder().isAscending() ? ASC : DESC, column));
}
return result.and(Sort.by(ASC, "o.id")); // tie-breaker
}A field name pasted into a query string is an injection hole, the lesson of SQL injection in Java. The map makes unknown fields harmless. The final sort by id is a tie-breaker: when many rows share a created date, the database may order them differently on each query, and a row appears on two pages or on none. With a unique tie-breaker the pages partition the result.
With Spring Data the page call is a Pageable, and in plain JPA it is setFirstResult(first).setMaxResults(pageSize). Whichever you use, fetch what the visible columns display and nothing more. A row that triggers a query per cell turns a 20-row page into 21 queries, which is the pattern in N plus 1.
Scope and size
Keep the model in a view-scoped bean so the table state survives the AJAX requests of one page view; a request-scoped bean would rebuild the model, and the table would forget its page. The scopes are compared in bean scopes. Cap rowsPerPageTemplate so nobody can request 100,000 rows in one go, and remember that the rows of the current page are held in the view state, whose growth is the subject of view state size. A 100-row page of wide entities is still a lot of data per user.
Where lazy tables go slow
The first trap is the count. A select count(*) with filters on a large table can cost more than the page query, and it runs on every filter change. If exact totals do not matter, cache the count for a few seconds, or show "more than 10,000" and stop counting there. The second is filters on columns without indexes: the table lets the user filter any column you expose, so a customer name filter on an unindexed column scans the table on every keystroke. Index what you expose, or set filterDelay so the request fires after the user stops typing. The third is lazy associations. A cell that reads a lazy collection after the repository's transaction has ended raises a LazyInitializationException; fetch what the page needs inside the query.
Checking it works
Turn on SQL logging and click through one page, one sort and one filter. You should see one data query with limit and offset, one count query, and no per-row queries. If you see more, the fetch strategy is wrong. If the same page produces different rows twice, the sort has no tie-breaker.
Selection, export and the other features that assume a full list
Several table features were designed for an in-memory list and behave differently in lazy mode. "Select all" selects only the visible page, because the table cannot know the other rows. If users need to act on everything that matches a filter, add an explicit "all N matching rows" action that sends the filter criteria to the server and runs the operation there, not a list of ids. Export is the same: the built-in exporter writes the rows the table holds, so a CSV of 200,000 orders needs a dedicated download endpoint that streams from a cursor, with its own limits and its own permission check.
Row expansion and inline editing work, since they act on one row at a time, but remember that getRowData is called with the key when the user acts on a selected row. It must return the current row from the database, not a cached copy, or an edit applies to stale data. Pair editing with an optimistic lock, as in optimistic locking, so two editors cannot silently overwrite each other.
Keyboard use and accessibility of the table
Paging controls, sortable headers and filter inputs must work with a keyboard, and screen readers need to know which column is sorted. PrimeFaces provides ARIA attributes for the table, but custom column content, such as icon buttons, needs labels of its own. Test the page without a mouse once, and give every icon-only button a title. A lazy table that updates through AJAX should also announce changes, so keep the row count text visible near the paginator.
When a lazy table is more than you need
For a few hundred rows, an ordinary in-memory table with client-side sorting is simpler and faster for the user, since nothing round-trips. Lazy loading is justified once the data does not fit comfortably in a view. The reference is the PrimeFaces DataTable documentation, and the lazy loading showcase has a runnable page.


