How to implement a LazyDataModel with size in Primefaces
This solution is ideal if you have a list of entities or a named queries that return a list of entities. For example let's say we have...
https://www.czetsuyatech.com/2017/01/jsf-primefaces-lazydatamodel-with-size.html
This solution is ideal if you have a list of entities or a named queries that return a list of entities.
For example let's say we have an entity user and we want to return all the users with role=x.
Then we need to extend primefaces's LazyDataModel class, overriding the size method.
For example let's say we have an entity user and we want to return all the users with role=x.
@NamedQueries({ @NamedQuery(name = "User.listUsersByRoles", query = "" + "SELECT u FROM User u" + " LEFT JOIN u.roles as role" + " WHERE role.name IN (:roleNames)) }) public class User implents Serializeable { }
Then we need to extend primefaces's LazyDataModel class, overriding the size method.
import org.primefaces.model.LazyDataModel; public class LazyDataModelWSizeNext we need a service that will call the native query:extends LazyDataModel { private static final long serialVersionUID = -20655217804181429L; public Integer size() { return getRowCount(); } }
public ListAnd finally a bean that will call the service. Let's say we want to query all the users with role admin and hr.listUsersByRoleList roleNames) { List users = null; try { users = entityManager.createNamedQuery("User.listUsersByRoles").setParameter("roleNames", roleNames).getResultList(); } catch (Exception e) { log.error("null {}", e.getMessage()); } return users; }
private LazyDataModelfilteredUsers = null; public LazyDataModel getFilteredLazyDataModel() { if (filteredUsers != null) { return filteredUsers; } filteredUsers = new LazyDataModelWSize () { private static final long serialVersionUID = 1L; @Override public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map loadingFilters) { List entities = null; entities = userService.listUsersByRoles(Arrays.asList("ADMIN", "HR")); setRowCount(entities.size()); return entities.subList(first, (first + pageSize) > entities.size() ? entities.size() : (first + pageSize)); } }; return filteredUsers; }
Post a Comment