Jakarta EE Components

PrimeFaces Lazy Data Model

Turn a JPA entity into a lazy-loaded PrimeFaces table with paging, sorting, filtering and cursor pagination, in a few lines of code.

JPALazyDataModel connects a PrimeFaces DataTable to JPA with very little code. You can @Inject it, it needs no inheritance, and it is built on the same JPAFinder queries as the rest of Flow Logix.

It is fully serializable, so it works in clustered sessions such as those of Payara and Hazelcast. Your entity classes and the model’s initialization lambdas don’t need to be serializable themselves.

Why not PrimeFaces' own JPA model?

PrimeFaces now provides its own JpaLazyDataModel. Flow Logix JPALazyDataModel predates it. Our model is simpler to use, more compact and, above all, can be injected with CDI. It is unique in not requiring your entities to be serializable. For large datasets, it supports cursor pagination.

Basic usage

Point the DataTable at the model:

userviewer.xhtml
<p:dataTable lazy="true" value="#{userViewer.lazyModel}" var="user">
    ... specify columns as usual ...
</p:dataTable>

Then inject the model into a view-scoped bean:

UserViewer.java
@Named
@ViewScoped
public class UserViewer implements Serializable {
    @Inject
    @Getter
    // optional configuration annotation
    @LazyModelConfig(caseInsensitive = true)
    JPALazyDataModel<UserEntity> lazyModel;
}

This model filters case-insensitively. You can configure it further in a @PostConstruct method, with initialize() and the builder methods described below.

Installation

<dependencies>
    <dependency>
        <groupId>com.flowlogix</groupId>
        <artifactId>flowlogix-datamodel</artifactId>
        <version>11.7.7</version>
    </dependency>
</dependencies>

Create the model without injection

UserViewer.java
@Named
@ViewScoped
public class UserViewer implements Serializable {
    private final @Getter JPALazyDataModel<UserEntity> userModel =
            JPALazyDataModel.create(builder -> builder.entityClass(UserEntity.class).build());
}

Configuration options

Only entityClass is required. Everything else is optional.

Option Description

entityManager

An EntityManager Supplier. By default, it is injected with CDI.

entityManagerQualifiers

Qualifier annotations that select the EntityManager to inject.

caseSensitiveFilter

Whether filtering String values is case-sensitive. The default is true.

filterCaseConversion

UPPER or LOWER: how values are converted for case-insensitive filtering. The default is UPPER.

wildcardSupport

Whether wildcards are supported in EXACT and other String queries. The default is false.

joinType

The jakarta.persistence.criteria.JoinType used for dotted (nested) field references in filters and sorting. The default is LEFT, so entities whose to-one associations are null are still returned when sorting or filtering on those associations' columns. Use INNER (or @LazyModelConfig(innerJoins = true)) only if your application deliberately relies on inner join semantics.

sorter

Additional or replacement sort criteria.

filter

Additional or replacement filter criteria.

optimizer

Further customizations of the queries, such as JPA hints. Works together with JPAFinder.

cursor

Use cursor pagination instead of offset pagination.

resultEnricher

A transformation of the query results, such as adding or changing the rows the model displays.

converter

A Function that converts the String form of a primary key into a primary key object. Needed only if the default is insufficient.

keyConverter

A Function that converts an entity into its primary key, in String form. Needed only if the default is insufficient.

Note
Dotted (nested) field references, such as address.city, share a single LEFT join per query between filter, sort and count criteria. Filtering over a to-many association uses DISTINCT (and COUNT(DISTINCT …​) for the count query), so each matching entity is returned exactly once, and count() always agrees with the paged rows.

Customize the model

Sorting

Add the zip code to the default sort with custom criteria:

@Named
@ViewScoped
public class SortingDataModel implements Serializable {
    @Inject
    @Getter
    JPALazyDataModel<UserEntity> userModel;

    @PostConstruct
    void initialize() {
        userModel.initialize(builder -> builder.sorter((sortData, cb, root) ->
                // Example: add an ascending zip code-based sort order
                sortData.applicationSort(UserEntity_.zipCode.getName(),
                                var -> cb.asc(root.get(UserEntity_.zipCode)))
                        // Example: if user requests zip code-based sort order,
                        // add address-based sort order to mirror the zip code-based sort order
                        .applicationSort(UserEntity_.zipCode.getName(), UserEntity_.address.getName(), sortData,
                                // user requested ascending sort order
                                () -> cb.asc(root.get(UserEntity_.address)),
                                // user requested descending sort order
                                () -> cb.desc(root.get(UserEntity_.address)),
                                // user did not request a sort order
                                () -> null
                        )).build());
    }
}

Filtering

Replace a filter with the replaceFilter convenience method. Here, only zip codes greater than the one in the filter are returned:

@Named
@ViewScoped
public class FilteringDataModel implements Serializable {
    @Inject
    @Getter
    JPALazyDataModel<UserEntity> userModel;

    @PostConstruct
    void initialize() {
        // display only zip codes greater than the filter field
        userModel.initialize(builder ->
                builder.filter((filters, cb, root) -> filters.replaceFilter(UserEntity_.zipCode.getName(),
                                (Predicate predicate, Integer value) -> cb.greaterThan(root.get(UserEntity_.zipCode), value)))
                        .build());
    }
}

Cursor pagination

With large datasets, cursor pagination performs better than offset pagination. It also works with infinite scroll. It requires Flow Logix DataModel 11.2 or newer.

To use it, add cursor(CursorPagination.create(List<Field>, …​)) to the model’s initializer. The order of the fields matters:

  • The first field is the default cursor and the unique tiebreaker. When the user hasn’t chosen a sort order, the data is sorted by this field, which cursor pagination requires.

  • When the user sorts by another field in the list, that field may be used as the cursor instead.

  • When the user sorts by a field that isn’t in the list, the model falls back to offset pagination.

Cursor pagination works best when the fields used for sorting are indexed in the database.

UserViewer.java
@Named
@ViewScoped
public class UserViewer implements Serializable {
    @Inject
    @Getter
    JPALazyDataModel<UserEntity> userModel;

    @PostConstruct
    void initialize() {
        // configure cursor pagination by id field
        userModel.initialize(builder ->
                builder.cursor(CursorPagination.create(config -> config.supportedFields(
                        List.of(new Field<>(() -> UserEntity_.id.getName(), UserEntity::getId)
                        )).build())).build());
    }
}

Here, cursor pagination is used when the data is unsorted, or sorted by UserEntity.id.

Note
A high-priority application sort is not supported with cursor pagination, and is ignored when it is enabled, because the high-priority sort would have to be the same as the cursor field, and changing it would cause unexpected behavior.

How it works

Offset pagination becomes slower as the offset grows. Cursor pagination instead remembers the position of the last row seen (the cursor) and uses it as additional criteria to fetch the next page, so the database can go straight to the next rows. This keeps response times fast, especially with large datasets.

Each time a page of data arrives, its last cursor value is cached. Keep cursor values small, such as an integer, UUID or short string, so the cursor cache doesn’t use too much memory. Cache eviction can be configured with the evictCursor* and *CursorWindowSize parameters.

The cursor position is an ordering tuple: the value of the sort column on the last row of the page, plus the value of the first configured field on the same row. The first configured field must be stable and unique (such as id or createdDate), because it is appended to every cursor query’s ORDER BY as an ascending tiebreaker, which makes the ordering total. The cursor predicate is then lexicographic:

sort > value OR (sort = value AND tiebreaker > tiebreakerValue)

It is reversed for descending order, so rows whose sort value equals the value at the page boundary are never skipped or repeated, even when the sort column has duplicates that span a page boundary.

Batch fetching with optimizer hints

Optimizer hints can fetch dependent entities in batches, with an IN query. The UnaryOperator should return the same TypedQuery instance it was given, in the fluent style:

@Named
@ViewScoped
public class OptimizedDataModel implements Serializable {
    @Inject
    @Getter
    JPALazyDataModel<UserEntity> userModel;

    @PostConstruct
    void initialize() {
        // optimize query by batching relationship fetching
        userModel.initialize(builder ->
                builder.optimizer(query -> query
                                .setHint(QueryHints.BATCH, getResultField(UserEntity_.userSettings.getName()))
                                .setHint(QueryHints.BATCH, getResultField(UserEntity_.alternateEmails.getName()))
                                .setHint(QueryHints.BATCH_TYPE, BatchFetchType.IN))
                        .build());
    }
}

Post-processing results

A results enricher can post-process the query results. This one adds a row:

@Named
@ViewScoped
public class EnrichedDataModel implements Serializable {
    @Inject
    @Getter
    JPALazyDataModel<UserEntity> userModel;

    @PostConstruct
    void initialize() {
        // enrich returned results from the model
        userModel.initialize(builder -> builder.resultEnricher(EnrichedDataModel::addLastRow).build());
    }

    private static List<UserEntity> addLastRow(List<UserEntity> list) {
        list.add(UserEntity.builder().userId("golden").fullName("Golden User").build());
        return list;
    }
}

Selecting a persistence unit

Use @LazyModelConfig(entityManagerSelector) with a CDI qualifier to choose the EntityManager for this model:

@Named
@ViewScoped
public class QualifiedDataModel implements Serializable {
    @Inject
    @Getter
    @LazyModelConfig(entityManagerSelector = NonDefault.class)
    JPALazyDataModel<UserEntity> userModel;
}

Primary key converters

PrimeFaces' LazyDataModel converts between entities and the String form of their primary keys, in getRowKey(String) and getRowKey(TT). Default converters are provided. If they aren’t sufficient, override them with the converter and keyConverter builder methods. This example represents the primary key as a binary value:

@Named
@ViewScoped
public class ConverterDataModel implements Serializable {
    @Inject
    @Getter
    JPALazyDataModel<UserEntity> userModel;

    @PostConstruct
    void initialize() {
        userModel.initialize(builder -> builder
                // key is stored as binary string
                .converter(binaryString -> new BigInteger(binaryString, 2).longValue())
                .keyConverter(entity -> Long.toBinaryString(entity.getId()))
                .build());
    }
}