About Hebert Coelho

Senior Java Development, with 4 certifications and a published book about JSF (portuguese only). Founder of the blog uaiHebert.com visited from more than 170 different countries.

Lazy JSF Primefaces Datatable Pagination – Part 2

The page code is very simple and there is no complication. Check the “index.xhtml” code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
    <f:view>
        <h:form>
            <p:dataTable id="lazyDataTable" value="#{playerMB.allPlayers}" var="player" paginator="true" rows="10"
                selection="#{playerMB.player}" selectionMode="single"
                paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                rowsPerPageTemplate="5,10,15" style="width: 80%;margin-left: 10%;margin-right: 10%;">

                <p:ajax event="rowSelect" update=":playerDialogForm" oncomplete="playerDetails.show()" />

                <p:column>
                    <f:facet name="header">Name</f:facet>
                    <h:outputText value="#{player.name}" />
                </p:column>
                <p:column>
                    <f:facet name="header">Age</f:facet>
                    <h:outputText value="#{player.age}" />
                </p:column>
            </p:dataTable>
        </h:form>

        <p:dialog widgetVar="playerDetails" header="Player" modal="true">
            <h:form id="playerDialogForm">
                <h:panelGrid columns="2">
                    <h:outputText value="Id: " />
                    <h:outputText value="#{playerMB.player.id}" />
                    <h:outputText value="Name: " />
                    <h:outputText value="#{playerMB.player.name}" />
                    <h:outputText value="Age: " />
                    <h:outputText value="#{playerMB.player.age}" />
                </h:panelGrid>
            </h:form>
        </p:dialog>
    </f:view>
</h:body>
</html>

We got a lazy datatable that will display a selected value in a dialog.

In our Managed Bean we have a simpler code than the page:

package com.mb;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.model.LazyDataModel;

import com.model.Player;

@ViewScoped
@ManagedBean
public class PlayerMB implements Serializable {

    private static final long serialVersionUID = 1L;
    private LazyDataModel<Player> players = null;
    private Player player;

    public LazyDataModel<Player> getAllPlayers() {
        if (players == null) {
            players = new PlayerLazyList();
        }

        return players;
    }

    public Player getPlayer() {
        if(player == null){
            player = new Player();
        }

        return player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }
}

We got a get/set to the Player entity and a get to the an object of the LazyDataModel type.
Check bellow the implementation of the PlayerLazyList code

package com.mb;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.connection.MyTransaction;
import com.dao.PlayerDAO;
import com.model.Player;

public class PlayerLazyList extends LazyDataModel<Player> {

    private static final long serialVersionUID = 1L;

    private List<Player> players;

    private MyTransaction transaction;

    private PlayerDAO playerDAO;

    @Override
    public List<Player> load(int startingAt, int maxPerPage, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        try {
            try {
                transaction = MyTransaction.getNewTransaction();
                playerDAO =  new PlayerDAO(transaction);

                transaction.begin();

                // with datatable pagination limits
                players = playerDAO.findPlayers(startingAt, maxPerPage);

                // If there is no player created yet, we will create 100!!
                if (players == null || players.isEmpty()) {
                    playerDAO.create100Players();

                    // we will do the research again to get the created players
                    players = playerDAO.findPlayers(startingAt, maxPerPage);
                }
            } finally {
                transaction.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // set the total of players
        if(getRowCount() <= 0){
            setRowCount(playerDAO.countPlayersTotal());
        }

        // set the page dize
        setPageSize(maxPerPage);

        return players;
    }

    @Override
    public Object getRowKey(Player player) {
        return player.getId();
    }

    @Override
    public Player getRowData(String playerId) {
        Integer id = Integer.valueOf(playerId);

        for (Player player : players) {
            if(id.equals(player.getId())){
                return player;
            }
        }

        return null;
    }
}

About the code above:

  • The load method: the Primefaces will invoke this method every time that the pagination is fired. It will have all parameters with valid values; with these parameters you will be able to do a query in the database getting only for the needed data. If you want to sort your query by a field you can use the sortField attribute that will have the column datatable value (it will be null if the user do not order); the sortOrder will indicate if the user wants ascending or descending.
  • The getRowKey method: this method return an id to each line, the Primefaces will invoke this method when needed.
  • The getRowData method: will return a selected Player in the datatable.
  • When you run this application the first time it will persist 100 players in the database. In a real application this would not be necessary. 

A last configuration need to be added in the “web.xml” file:

<persistence-context-ref>
    <persistence-context-ref-name>JSFPU</persistence-context-ref-name>
    <persistence-unit-name>JSFPU</persistence-unit-name>
</persistence-context-ref>

We will use this configuration to do the JNDI Lookup.

Running our application

Now we just need to start up the application.

To access the application you can use the link:

http://localhost:8080/DatatableLazyPrimefaces/

Click here to download the source code of this post.

Reference: Lazy JSF Datatable Pagination (Primefaces) from our JCG partner Hebert Coelho at the uaiHebert blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

2 Responses to "Lazy JSF Primefaces Datatable Pagination – Part 2"

  1. cock says:

    bulllllcheeeeat

Leave a Reply


six × 9 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books