<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Benny's Blog &#187; paging</title>
	<atom:link href="http://blog.projectnibble.org/tag/paging/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.projectnibble.org</link>
	<description>House Of Code</description>
	<lastBuildDate>Fri, 13 Aug 2010 15:06:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Java generic paged lazy List with JSF/JPA example implementation</title>
		<link>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/</link>
		<comments>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 12:58:53 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[lazy loading]]></category>
		<category><![CDATA[paging]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[richfaces]]></category>

		<guid isPermaLink="false">http://blog.projectnibble.org/?p=310</guid>
		<description><![CDATA[Here&#8217;s a list implementation I came up with to enable true paged data fetching completely transparent to any user. It works independent of persistence layers, such as JPA implementations etc. download PagedList Lazy loading with the PagedList Originally I made the PagedList because I needed paged data fetching using JMS queues for a JSF Rich [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a list implementation I came up with to enable true paged data fetching completely transparent to any user. It works independent of persistence layers, such as JPA implementations etc.</p>
<ul>
<li><a href="http://projectnibble.org/dump/blog/pagedlist/PagedList.rar">download PagedList</a></li>
</ul>
<p><span id="more-310"></span></p>
<h3>Lazy loading with the PagedList</h3>
<p>Originally I made the PagedList because I needed paged data fetching using JMS queues for a JSF Rich datatable and datascroller; a common problem in JSF but less commonly solved, even less documented and less still solved in an elegant way. Most people are able to solve this problem by using an <a href="https://www.hibernate.org/43.html">OpenSessionInView</a> antipattern (keeping Hibernate-oid session open until the view requests the lazy loaded data) but since I&#8217;m using JMS queue, this was not an option. I decided to circumvent the entire JSF to JMS queue integration by providing my data in a paging lazy list. It works beautifully.</p>
<pre  name="code" class="java">
public class PagedList&lt;Dto, QueryParameters&gt; extends AbstractList&lt;Dto&gt; {

    private final QueryParameters queryParameters;

    private final PagedDataProvider&lt;Dto, QueryParameters&gt; pagedDataProvider;

    private final Map&lt;Integer, List&lt;Dto&gt;&gt; fetchedPages;

    private final int dataSize;

    private final int pageSize;

    public PagedList(PagedDataProvider&lt;Dto, QueryParameters&gt; pagedDataProvider, QueryParameters queryParameters) {
        this.pagedDataProvider = pagedDataProvider;
        this.queryParameters = queryParameters;
        fetchedPages = new HashMap&lt;Integer, List&lt;Dto&gt;&gt;();
        dataSize = pagedDataProvider.getDataSize();
        pageSize = pagedDataProvider.getPageSize();
    }

    public Dto get(int index) {
        int pageNr = (int) Math.floor(index / pageSize);
        if (fetchedPages.get(pageNr) == null) {
            fetchedPages.put(pageNr, pagedDataProvider.provide(pageNr, queryParameters));
        }
        return fetchedPages.get(pageNr).get(index % pageSize);
    }

    public int size() {
        return dataSize;
    }
}
</pre>
<p>It is different from <a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/list/LazyList.html">Apache&#8217;s LazyList</a> (and many other implementations) in that it relies on an external dataprovider to provide the dataset&#8217;s total size, pagesize and data provision itself. For example, using my lazy list version the <i>size()</i> method actually returns the total size of data potentially available, not just physically available in the list at the present. This way the list works completely transparent to its users. Also, there is no simple factory being passed in that creates dummy objects or something: actual remote data is being fecthed in pages by a data provider. Pages being fetched are independent of each other; when requesting page 5, page 1 through 4 are not need or fetched.</p>
<p>The PagedList works in combo with a <em>PagedDataProvider</em> interface that external dataproviders (some dao for example) could implement. So it has no dependencies whatsoever on some specific implementation. The paged data provider provides the total size of the dataset, the page size and pages of the dataset itself when needed.</p>
<h3>Example implementation for JSF and JPA dao</h3>
<p>Here&#8217;s an example implementation which ties a JSF Richfaces datatable to a JPA dao using a PagedList. I cut out the service layer, view handlers/controllers and whatnot for sake of simplicity.</p>
<pre  name="code" class="xhtml">
&lt;rich:dataTable id="searchResults" value="#{appleService.apples}" var="apple"&gt;
...
&lt;/rich:dataTable&gt;
</pre>
<pre  name="code" class="java">
/**
 * JPA dao which acts as paged data provider for the paged list.
 *
 * Relies on two JPA named queries specified on the Entity being fetched.
 *
 * @author Benny Bottema
 * @see PagedDataProvider
 */
public class AppleJPADao implements AppleDao, PagedDataProvider&lt;AppleDto, AppleQueryParameters&gt; {

    // entitymanager stuff omitted for example (real world: injected by Spring)

    private static final int PAGESIZE = 50;

    /**
     * @see AppleDao#getAllApples(String, String)
     */
    public List&lt;AppleDto&gt; getAllApples(String type, String quality) {
        // optional query parameters: can be null
        AppleQueryParameters params = new AppleQueryParameters();
        params.setAppleType(type);
        params.setAppleQuality(quality);
        return new PagedList&lt;AppleDto, AppleQueryParameters&gt;(this, params);
    }

    /**
     * @see PagedDataProvider#provide(int, Object)
     */
    public List&lt;AppleDto&gt; provide(int page, AppleQueryParameters queryCriteria) {
        Query query = entityManager.createNamedQuery("Apple.findAll");
        query.setParameter("appleType", queryCriteria.getAppleType());
        query.setParameter("appleQuality", queryCriteria.getAppleQuality());
        // JPA's paging mechanism
        query.setFirstResult(PAGESIZE * page);
        query.setMaxResults(PAGESIZE);
        return (List&lt;AppleDto>) query.getResultList();
    }

    /**
     * @see PagedDataProvider#getDataSize()
     */
    public int getDataSize() {
        Query countQuery = entityManager.createNamedQuery("Apple.count");
        return ((Long) countQuery.getSingleResult()).intValue();
    }

    /**
     * @see PagedDataProvider#provide()
     */
    public int getPageSize() {
        return PAGESIZE;
    }
}
</pre>
<h3>Known issues</h3>
<p>So far there is only one known issue, which is more of a problem with lazy loading in general: synchronizing the lazy loading list with the remote dataset to avoid becoming stale when changes happen to the dataset. Example: when the dataset changes, the size of the list is not being updated and the <i>get()</i> method may try to fetch wrong or even unavailable data throwing an exception. Since I&#8217;m using the paged list in a limited way, I&#8217;ve not yet encountered this problem. </p>
<p>One way would be to solve this problem for the Rich datable and datascroller specifically is to have a a4j poll component that listens for dataset changes on the server and refreshes the entire datatable as necessary. Just thinking out loud here&#8230;</p>
<p><a href="http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
