This Sample Store Catalog app demonstrates the usage of JavaServer Faces, the new Java Persistence APIs, and Spring 2.0 to implement pagination. I took this example Pagination of Data Sets in a Sample Application using JSF, Catalog Facade Stateless Session, and Java Persistence APIs and modified it slightly to use a Spring Bean instead of a EJB 3.0 Stateless Session Bean. If you compare the two, you will see that the code is almost the same, the main difference is the extra xml configuration for Spring, and for me it wasn't easy to get the .xml configuration right. It took looking at several articles, blogs, examples, and some trial and error to get it working. (see the references at the end).
download the SpringJPA sample application code
Note: I updated the Spring JSF integration part of this application to use
the
org.springframework.web.jsf.DelegatingVariableResolver instead of a
JSF Managed Bean ServiceLocator in order to get a reference to the CatalogService Spring Bean from the Spring application context.
Explanation of the usage of JSF, Spring 2.0 , and Java Persistence APIs in a sample Store Catalog Application The image below shows the Catalog Listing page, which allows a user to page through a list of items in a store.
The List.jsp page uses a JSF dataTable component to display a list of catalog items
The dataTable component is useful when you want to show a set of results in a table. In a JavaServer Faces application, the UIData component (the superclass of dataTable) supports binding to a collection of data objects. It does the work of iterating over each record in the data source. The HTML dataTable renderer displays the data as an HTML table.
In the List.jsp web page the dataTable is defined as shown below: (Note: Red colors are for Java EE tags, annotations code, Blue for Spring specific and Green for my code or variables)
Code Sample from: List.jsp
|
<h:dataTable value='#{item.items}' var='dataTableItem' border="1"
cellpadding="2" cellspacing="0">
|
The value attribute of a dataTable tag references the data to be included in the table. The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable. In the dataTable tag from the List.jsp page, the value attribute points to a list of catalog items. The var attribute points to a single item in that list. As the UIData component iterates through the list, each reference to dataTableItem points to the current item in the list.
The dataTable's value is bound to the items property of the item controller class, ItemController , which is defined in the faces-config.xml file:
| Code Sample from: faces-context.xml |
<managed-bean>
<managed-bean-name>item</managed-bean-name>
<managed-bean-class>
sessionpagination.ItemController
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>catalogService</property-name>
<value>#{catalogService}</value>
</managed-property>
</managed-bean>
|
This ItemController ManagedBean
items property is defined as shown below:
| Code Sample from: ItemController.java |
public DataModel getItems() {
if (model==null || index != firstItem){
model=getNextItems();
}
return this.model;
}
public DataModel getNextItems() {
model = new ListDataModel(catalogService.getItems(firstItem,batchSize));
index = firstItem;
return this.model;
}
|
The getItems() method wraps a List of item objects, returned from the catalogService, in a DataModel.
UIData, the superclass of dataTable, supports data binding to a collection of data objects represented by a DataModel instance. The data collection underlying a DataModel instance is modeled as a collection of row objects that can be accessed by a row index. The APIs provide mechanisms to position to a specified row index, and to retrieve an object that represents the data that corresponds to the current row index.
The Item properties Name, Photo, and price are displayed with the column component:
Code Sample from: List.jsp
|
<h:column>
<f:facet name="header">
<h:outputText value="Price"/>
</f:facet>
<h:outputText value="#{dataTableItem.price}"/>
</h:column>
|
The column tags represent columns of data in a UIData component. While the UIData component is iterating over the rows of data, it processes the UIColumn component associated with each column tag for each row in the table.
The UIData component iterates through the list of items ( item.items) and displays the dataTableItem.price. Each time UIData iterates through the list of items, it renders one cell in each column.
The dataTable and column tags use facet to represent parts of the table that are not repeated or updated. These include headers, footers, and captions.
The recommended way to integrate Spring with JSF is to configure the Spring DelegatingVariableResolver
in the faces-context.xml. The <application> <variable-resolver> elements in a faces-config.xml file allows a Faces-based application to register a custom replacement class for the implementation of the standard Faces VariableResolver implementation. The Spring DelegatingVariableResolver
first delegates to the original resolver of the underlying JSF implementation, then to the Spring root WebApplicationContext. This allows you to configure Spring Beans as managed properties of your JSF Managed Beans. For example, below the catalogService Spring Bean is configured as a managed property of the ItemController JSF ManagedBean:
| Code Sample from: faces-context.xml |
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
<managed-bean>
<managed-bean-name>item</managed-bean-name>
<managed-bean-class>
sessionpagination.ItemController
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>catalogService</property-name>
<value>#{catalogService}</value>
</managed-property>
</managed-bean>
|
The catalogService, and its implementation CatalogDAO , is defined as a Spring bean in the Spring configuration resource file /WEB-INF/applicationContext.xml :
| Code Sample from: applicationContext.xml |
<bean id="catalogService" class="service.CatalogDAO"/>
<bean name="itemController" class="sessionpagination.ItemController">
<property name="catalogService">
<ref bean="catalogService"/>
</property>
</bean>
</beans>
|
<property name="catalogService"> refers to the ItemController setCatalogService method. The Spring root WebApplicationContext will inject the catalogService Spring Bean into the catalogService property of the ItemController JSF ManagedBean :
| Code Sample from: ItemController.java |
public class ItemController {
private CatalogService catalogService ;
public void setCatalogService(CatalogService catalogService) {
this.catalogService = catalogService;
}
|
For more information on using JSF with Spring, see Spring - Java/J2EE Application Framework Integrating with JavaServer Faces .
Using the Java Persistence API (JPA) with Spring 2.0 The Spring bean CatalogDAO uses the Java Persistence API EntityManager Query object to return a list of items. The CatalogDAO annotates the field private EntityManager em; with @PersistenceContext
, which causes an entity manager to be injected. (note that using the @PersistenceContext annotation is the same way an Entity Manager is injected for a EJB 3.0 Session Bean .)
| Code Sample from: CatalogDAO.java |
@Repository
@Transactional
public class CatalogDAO implements CatalogService {
@PersistenceContext(unitName="PetCatalogPu")
private EntityManager em;
public List<Item> getItems(int firstItem,int batchSize) {
Query q = em.createQuery("select object(o) from Item as o");
q.setMaxResults(batchSize);
q.setFirstResult(firstItem);
List<Item> items= q.getResultList();
return items;
}
|
The Java Persistence Query APIs are used to create and execute queries that can return a list of results. The JPA Query interface provides support for pagination via the setFirstResult() and setMaxResults() methods: q.setMaxResults(int maxResult) sets the maximum number of results to retrieve. q.setFirstResult(int startPosition) sets the position of the first result to retrieve. In the code below, we show the Item entity class which maps to the ITEM table that stores the item instances. This is a typical Java Persistence entity object. There are two requirements for an entity:
annotating the class with an @Entity annotation.
annotating the primary key identifier with @Id
Because the fields name, description.... are basic mappings from the object fields to columns of the same name in the database table, they don't have to be annotated. The O/R relationships with Address and Product are also annotated. For more information on defining JPA entities see Pro EJB 3: Java Persistence API book.
| Code Sample from: Item.java |
@Entity
public class Item implements java.io.Serializable {
@Id
private String itemID;
private String name;
private String description;
private String imageurl;
private String imagethumburl;
private BigDecimal price;
@OneToOne(cascade={CascadeType.PERSIST})
private Address address;
@ManyToOne
private Product product;
public Item() { }
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setAddress(Address addre |