Preparing the backend for lazy loading

Lazy loading (and filtering) capabilities should be delegated to the backend as much as possible. Although the Grid class itself is able to cache some of the data and send it to the client only when needed, it cannot prevent you from querying the whole database, for example. In order to support lazy loading, backend services should provide the means to lazily load the data.

Typically, the UI gets the data from a service or repository class. Let's see an example of how a repository class can provide methods with lazy loading capabilities. The CallRepository class could define a findAll method that queries a slice of the rows in the Call table, as follows:

public class CallRepository {

    public static List<Call> findAll(int offset, int limit) {
        ...
    }

public static int count() {
...
} }

In the previous code, limit is used to limit the number of rows (actually, instances of User) that should be returned. When using SQL, this can be used as the LIMIT clause in a SQL query. offset is used to skip a number of rows, which is equivalent to the starting row number. For example, if the SQL table has 100 rows, and we use offset=10 and limit=5, the method should return only the rows 10 to 15. If we use offset=98 and limit=5, the method should return rows 98 to 100 (there are not enough rows left after 98 to complete a set of five rows).

For reference, here's what a JPA implementation of these methods could look like:

public class CallRepository {
...

public static List<Call> find(int offset, int limit) {
return JPAService.runInTransaction(em -> {
Query query = em.createQuery("select c from Call c");
query.setFirstResult(offset);
query.setMaxResults(limit);

List<Call> resultList = query.getResultList();
return resultList;
});
}

public static int count() {
return JPAService.runInTransaction(em -> {
Query query = em.createQuery("select count(c.id) from Call c");

Long count = (Long) query.getSingleResult();
return count.intValue();
});
}
}

Notice how we included a count method in the previous snippet of code. This is required in some situations, such as when using lazy loading with the Grid component.

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

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