Tuesday, July 12, 2011

Pagination with LazyDataModel loading from Spring Service in Primefaces

DataTable component in Primefaces is very powerful and flexible. It provides LazyDataModel mechanism to load pagination data. Here is my note about how to invoke injected Spring service to load data from database.

1. Integrate Spring and JSF



2. Inject Spring Service in JSF Bean

@ManagedBean(name = "bookBean")
public class BookBean implements Serializable {

 private BookService bookService;

3. Lazy init LazyDataModel.
private LazyDataModel lazyModel;

 public LazyDataModel getLazyModel() {
  if (lazyModel == null) {
   lazyModel = new LazyDataModel() {

    public List load(int first, int pageSize,
      String sortField, SortOrder sortOrder,
      Map filters) {
     return bookService.findAllInRange(first, first + pageSize);
  return lazyModel;

 public void setLazyModel(LazyDataModel lazyModel) {
  this.lazyModel = lazyModel;

4. JSF page