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



 
  org.springframework.web.jsf.el.SpringBeanFacesELResolver


 


2. Inject Spring Service in JSF Bean

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


 @ManagedProperty("#{bookService}")
 private BookService bookService;
}

3. Lazy init LazyDataModel.
private LazyDataModel lazyModel;

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

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

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

4. JSF page