Search code examples
jsf-2primefacesdatatable

Is primefaces live scrolling compatible with Lazy loading


I have a datatable where huge data sets need to be displayed.So i decided to go with primefaces live scrolling.I also got to know that to improve datatable performance with huge data sets we need to implement lazy loading.With reference to the primefaces showcase example here,what i observed that there in the statement

, a LazyDataModel needs to be implemented to query the datasource when pagination, sorting, filtering or live scrolling happens

live scrolling is mentioned but i cannot see the code to handle scrolling.It only has the code to handle sorting,filtering,row count and pagination.Can someone please clarify my confusion if both live scolling and lazy datamodel implementation are compatible with each other or should i add some code to handle live scrolling also.


Solution

  • It works exactly the same as if you were having a pagination.

    Here's a small example:

    xhtml

    <p:dataTable var="user"
            value="#{bean.lazyDataModel}"
            scrollRows="20"
            liveScroll="true"
            scrollHeight="500"
            lazy="true"
            scrollable="true">
    
            <p:column headerText="name">
               <h:outputText value="#{user.name}" />
            </p:column>
    
    </p:dataTable>
    

    Bean

    @ManagedBean
    @ViewScoped
    public class Bean {
    
        private LazyDataModel<User> lazyDataModel;
    
        @EJB
        UserEJB userEJB;
    
        @PostConstruct
        public void init() {
           lazyDataModel = new LazyUserModel(userEJB);
        }
    
        public LazyDataModel<User> getLazyDataModel() {
            return lazyDataModel;
        }
    
        public void setLazyDataModel(LazyDataModel<User> lazyDataModel) {
           this.lazyDataModel = lazyDataModel;
        }
    
       //setters and getters for userEJB
    }
    

    LazyUserModel

    public class LazyUserModel extends LazyDataModel<User> {
       private Integer findAllCount;
    
       @EJB
       private UserEJB userEJB;
    
       public LazyUserModel(UserEJB userEJB) {
           this.userEJB = userEJB;
       }
    
    
       @Override
       public List<User> load(int first, int pageSize, String sortField, SortOrder sortOrder,
            Map<String, String> filters) {
    
           List<User> data = new ArrayList<User>();
           // pageSize is scrollRows="20" in the datatable
           data = userEJB.findAll(first, pageSize); 
           // findAll is using query.setFirstResult(first).setMaxResults(pageSize).getResultList()
    
          // rowCount
           if (findAllCount == null) {
               findAllCount = userEJB.findAllCount();
               this.setRowCount(findAllCount);
           }
    
           return data;
       }
    
    }
    

    Hope this helps.