Sample Application using JSF, Seam 2.0, and Java Persistence APIs on Glassfish V2
Posted by caroljmcdonald on January 27, 2008 at 10:58 PM EST
Sample Application using JSF, Seam 2.0,
and Java Persistence APIs on Glassfish V2
This Sample Store Catalog app demonstrates the usage of JavaServer Faces, a Catalog Stateful Session Bean, the Java Persistence APIs, and Seam 2. I took this example Sample Application using JSF, Catalog Facade Stateless Session, and Java Persistence APIs and refactored it to use Seam on Glassfish by following the steps in Brian Leonards blog Seam Refresh and the clickable list example in the Seam Tutorial.
Download the Seam Sample Application Code
Explanation of the usage of JSF, Seam, 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.
DataTable JSF component
The List.jsp page uses a JSFdataTable
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 Seam specific
and Green
for my code
or variables)Code Sample from: List.jsp |
|
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
attribute
of the CatalogBean
class:Code Sample from: CatalogBean.java |
|
The
@DataModel
Seam annotation exposes an attribute of type java.util.List to a JSF
page as an instance of javax.faces.model.DataModel.
The
<h: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. In this case, the DataModel is made available
in a session
context variable named items.When the List.jsp page is diplayed it will try to resolve the items context variable. Since this context variable is not initialized, Seam will call the
@Factory
method getItems(),
which performs a JPA query (see getNextItems() code below)
and results in a DataModel being
outjected. The @Factory
annotation tells Seam to invoke the getItems()
method to initialize the items value.The @Name Seam
annotation specifies catalog as
the application unique component name which Seam will use to resolve
references to the catalog
context variable. Seam will instantiate the
component
and bind a new instance to the context variable the first time JSF
encounters the variable name catalog.
The instance will be bound to the
context specified by the @Scope
Seam annotation. The CatalogBean
is a org.jboss.seam.ScopeType.SESSION
scoped component. This means that the JSF components can bind to
the catalog
managed bean without configuring this in the faces-config.xml.
The @Stateful EJB 3.0
annotation marks this as a Stateful EJB. A Stateful EJB is used because
the current chunk of items, and
the user's position in the count of items in the db table, is
maintained for the user's session.The
@Interceptors EJB
3.0 annotation registers the SeamInterceptor.class as
an EJB interceptor for this session bean component.The Seam framework uses EJB interceptors to perform bijection, context demarcation, validation, etc, (the interceptor could be defined in the ejb-jar.xml instead).
Column JSF component
On the List.jsp page the Item Name, Photo, and Price properties
are displayed with the
column component:Code Sample from: List.jsp |
<h:dataTable value='#{items}' var='dataTableItem'
border="1" <h:column> |
The column tags represent columns of data in the dataTable component. While the dataTable component is iterating over the rows of data, it processes the column component associated with each column tag for each row in the table. As the dataTable component iterates through the list, each reference to
dataTableItem points to the current item in the
list.The dataTable component iterates through the list of items and displays the names, photos, and prices. Each time the dataTable iterates through the list of items, it renders one row in each column.
The dataTable and column tags use facets to represent rows of the table that are not repeated or updated. These include headers, footers, and captions.
Java Persistence Query API
The CatalogBean
Session EJB uses the Java Persistence API Query object
to return a list of items.
With the @PersistenceContext annotation
the CatalogBean uses dependency injection to lookup and obtain a
Container Managed EntityManager .
Since the EntityManager can be container managed for EJB Session
Beans, the application does not
have to manage its lifecycle (i.e. call the
EntityManagerFactory.create() and EntityManager.close() methods).
Code Sample from: CatalogBean.java |
@DataModel @PersistenceContext(unitName="PetCatalogPu") |
Since this query is used for Read-Only browsing, the transaction attribute in this example is specified as NOT_SUPPORTED. Queries using transaction-scoped entity managers outside of a transaction are typically more efficient than queries inside a transaction when the result type is an entity.
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: query.setMaxResults(int maxResult) sets the maximum number of results to retrieve. query.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
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 |
@Id
@ManyToOne public String getName() { |
The
@Name
seam annotation specifies the (application unique) component name item,
which is used in
the Detail.jsp to display the selected item's
attributes. The @Scope
Seam annotation binds the item
instance to the org.jboss.seam.ScopeType.EVENT
context.The
CatalogBean
pages through the list of items
by
maintaining the firstItem
and batchSize
attributes and passing these as
parameters to the query.setFirstResult(int startPosition), query.setMaxResults(int maxResult)
methods.
The CatalogBean's scope is defined as org.jboss.seam.ScopeType.SESSION,
which corresponds to the JSF managed bean session scope.The
CatalogBean
itemCount
property is used to get and display
the number of Catologue items in the data base:Code Sample from: List.jsp |
|
The
CatalogBean
getItemCount()
method uses the JPA javax.persistence.Query
interface to get the count of
all items in the database item table:Code Sample from: CatalogBean.java |
private int itemCount = 0; public int getItemCount()
{itemCount =
((Long)q.getSingleResult()).intValue(); itemCount; |
A JSF
commandLink is used to provide a link to
click on to
display the next page of items. The commandLink
tag represents an HTML hyperlink and is rendered as an HTML <a> element. The commandLink
tag is used to submit an action
event to the application. Code Sample from: List.jsp |
|
This
commandLink action attribute
references the CatalogBean next()
method that calculates
the
next page's first row number and returns a logical outcome
String, which causes the List page to display the next page's
list .
This CatalogBean
next()
method is defined as shown below:Code Sample from: CatalogBean.java |
public String next() { |
The JavaServer Faces
NavigationHandler
matches the logical outcome, item_list
against the navigation rules
in the application configuration resource
file faces-config.xml to
determine which page to access next. In this case, the
JavaServer Faces implementation loads the List.jsp
page after this method returns.| Code Sample from: faces-config.xml |
<navigation-rule> |
A JSF
commandLink
is used to provide a link to click on to
display the previous page of items. This commandLink
action attribute
references the CatalogBean's
prev()
method that
calculates the
previous page's first row number and returns a logical outcome
String, which causes the List page to display the previous page of
items :Code Sample from: List.jsp |
|
This
CatalogBean
prev() method
is defined as shown
below: Code Sample from: CatalogBean.java |
public String prev()
{ |
A JSF commandLink is used to provide a link to click on to display a page with the item details. This
commandLink
action attribute
references the CatalogBean select()
method:Code Sample from: List.jsp |
|
With Seam if you use the
@DataModelSelection
with the @DataModel
annotation, when the user clicks on the link, Seam will propagate the
selected row from the DataModel into the
annotated attribute:Code Sample from: CatalogBean.java
|
|
The
@DataModelSelection
Seam annotation tells Seam to inject the DataModel
List
element corresponding to the clicked link into the item attribute.
The @Out
Seam annotation transfers the value of this attribute to the item
event context
variable, making it available to a
JSP page after the action
catalog.select
method execution. So when a row of the
dataTable is selected, the
selected row
is injected to the item
attribute of the CatalogBean Stateful bean, and then
outjected to the event context
variable named item
which is used in the Detail.jsp page to display
the item details. The
CatalogBean
select() returns a string, "item_detail", which
causes the Detail.jsp page to display
the item details. The JavaServer Faces NavigationHandler
matches the logical outcome, item_detail
against the navigation rules in the application configuration resource
file faces-config.xml to determine which page to
access next. In this case, the
JavaServer Faces implementation loads the Detail.jsp
page after this method returns.| Code Sample from: faces-config.xml |
|
The Detail.jsp uses the
outputText
component to display the item
properties:Code Sample from: Detail.jsp |
item.description}"
title="Description"/> |
Conclusion
This concludes the sample application which demonstrates how to use Seam with the JSF dataTable and DataModel to page through a list of Item Entities which are retrieved using the CatalogBean Stateful Session EJB methods which use the Java Persistence APIs.
Configuration of the Application
for Seam 2.0, JSF, JPA, running on Glassfish V2
First I recommend reading Brian Leonard's
blog Seam
Refresh . I will summarize
and update
those steps here:- Download
and install NetBeans 6.1 bundled with GlassFish V2
- Alternatively you can Download and install GlassFish V2 separately.
- Download
and extract Seam 2.0
- Download the Sample Application Code
To Open and Test Run the seampagination Project:
- Use the Resolve Reference Problems dialog to map the ejb and web modules to their project, which are subdirectories beneath the seampagination directory.
- After the references are resolved, right-click the seampagination project and select Open Required Projects.
- Right-click
the seampagination-EJBModule and select Resolve
Reference
Problems:
- browse to the Seam lib directory and select jboss-seam.jar
and
select Open. This should resove the reference to the following jars:
jboss-seam.jar, hibernate.jar,
hibernate-validator.jar,
hibernate-annotations.jar, hibernate-commons-annotations.jar,
javassist.jar, dom4j.jar, commons-logging.jar.
- browse to the Seam lib directory and select jboss-seam.jar
and
select Open. This should resove the reference to the following jars:
jboss-seam.jar, hibernate.jar,
hibernate-validator.jar,
hibernate-annotations.jar, hibernate-commons-annotations.jar,
javassist.jar, dom4j.jar, commons-logging.jar.
- Right-click the seampagination-WebModule and select Resolve
Reference
Problems:
- Browse to the seampagination-ejb directory which is a sub-directory below the seampagination directory and select Open Project Folder.
- Browse to the jboss-seam-ui.jar
found in Seam lib
directory. This should resolve the reference to the following
jars:
jboss-seam-ui.jar and
jboss-el.jar.
- Use Netbeans to create a new Enterprise Application
- Right-click the Libraries node of the EJBModule project , choose
Add Jar and add these jars:
- Seam \lib\jboss-seam.jar
- Seam \lib\hibernate.jar
- Seam \lib\hibernate-validator.jar
- Seam \lib\hibernate-annotations.jar
- Seam \lib\hibernate-commons-annotations.jar
- Seam \lib\javassist.jar
- Seam \lib\dom4j.jar
- Seam \lib\commons-logging.jar
- Right-click the Libraries node of the WebModule project ,
choose Add Jar and add these jars:
- your ejbModule
- Seam \lib\jboss-seam-ui.jar
- Seam \lib\jboss-el.jar
- create an empty seam.properties file in the seampagination-EJBModule src\conf Folder.
- add the following phase listener to your faces-config.xml
file under webpages web-inf:
<lifecycle>
<phase-listener>
org.jboss.seam.jsf.SeamPhaseListener
</phase-listener>
</lifecycle> - add the following context parameter
to your web.xml file
<context-param>
<param-name>
org.jboss.seam.core.init.jndiPattern
</param-name>
<param-value>
java:comp/env/your ear name/#{ejbName}/local
</param-value>
</context-param> - add the following listener class to your
web.xml file
<listener>
<listener-class>
org.jboss.seam.servlet.SeamListener
</listener-class>
</listener> - For any session EJB's referenced from the web, add EJB
references to your web.xml,
for example:
<ejb-local-ref>
<ejb-ref-name>your ear name/CatalogBean/local</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local-home/>
<local>your package name.Catalog</local>
<ejb-link>CatalogBean</ejb-link>
</ejb-local-ref> - For any EJB's referenced from the web add a Seam
interceptor to
the EJB, for example :
@Interceptors({org.jboss.seam.ejb.SeamInterceptor.class})
References:
- What's
new in Seam 2.0
- Seam Refresh
- Seam Tutorial
- Glassfish and Seam Tips
- JBoss
Seam: Simplicity and Power Beyond Java book
- Java BluePrints Solutions Catalog for the Java Persistence APIs contains a collection of topics and example applications.
- Java Persistence reference page on GlassFish Project
- Java EE tutorial, for good tutorial on JSF and JPA
- Pro EJB 3: Java Persistence API book
Related Topics >>
Blog Links >>
- Login or register to post comments
- Printer-friendly version
- caroljmcdonald's blog
- 1598 reads






Comments
by sippoy - 2009-04-12 12:08
I've deployed this seam 2.0 with jsf application but I don't know the URL to test the page, can you please let me know the URL to test this application?by sippoy - 2009-04-11 18:43
I've deployed this seam application but don't know the URL to access it. Can you please let me know the URL to access this application.by caroljmcdonald - 2009-02-22 18:17
I haven't tried seam-managed persistence, but I have read about it and there are examples in the book "seam in action", by Dan Allen. You use the @In annotion for seam managed persistence. Netbeans doesn't handle persistence or transactions either way, Glassfish and the persistence provider do that. Netbeans has a wizard for JPA that generates JPA entities from database tables, and queries for JSF pages or RESTful webservices. Netbeans does not have a wizard for seam, you can use the command line seam-gen for that, which you can also read about in the book seam in actionby telecomtom - 2009-02-19 12:36
Hello, great examples, good commentary. I was wondering, in regard to your other blog article that you referenced at the top of this article, could you extend or change the example to include Seam-managed persistence in Netbeans? And if you don't mind, also Seam-managed transactions, also in Netbeans? Or perhaps it would be easier at this point in time to just do it all in Eclipse? And that begs the question, how easy can you do Seam-managed persistence and transactions in Eclipse, if at all?by pecabo - 2008-02-14 03:17
Yes, I can :)))) Thank you for the hint :)by caroljmcdonald - 2008-02-13 08:09
the restapi is added by netbeans 6. can you just remove this from the librairies? otherwise I will upload a version with this removed.by pecabo - 2008-02-13 07:55
Bummer! But another question: if I use your example, I can't resolve the library problem: The project uses a class library called "restapi", but this class library was not found. What jars are bundled?by caroljmcdonald - 2008-02-13 07:40
Je ne sais pasby pecabo - 2008-02-13 07:34
I did it à la If you want to create your own Java EE application using Seam 2.0 on Glassfish V2 with Netbeans from scratch (read the steps in Brian Leonard's blog Seam Refresh but use the SEAM 2.0 jars listed here here): from the scrath with the help of netbeans6 and addes the necessary entries and the jars listed above :)by caroljmcdonald - 2008-02-13 07:13
Did you use the jars listed in this blog? Brian's example needs the jar in this blog to work. I don't know, you could ask in the Glassfish forum.by pecabo - 2008-02-13 07:01
Hi, I implemented the example of Brian Leonard with glassfish and Seam 2. But if I press the button, I get the exception javax.el.MethodNotFoundException: Method not found: de.barmenia.muv.seamNB6.service.ManagerActionLocal_9501578.sayHallo() I'm very suprised at the _9501578-extension. Have you any idea to fix my problem?by caroljmcdonald - 2008-02-07 16:12
Yes I did implement a sample catalog app with Spring 2.5, see my previous blog entry. (but its not Seam and Spring together)by disa - 2008-02-07 16:07
Hello! Did you try it with Spring 2.5? I get Validation Error (invalid stack size) when trying to use @Transactional and my aspect both under Spring 2.5. It seems that something wrong with CGLIB. I'm running my application with spring-agent and Spring JUnit integration annotation.by cayhorstmann - 2008-01-28 23:31
Venkatesh's example is interesting too, but what's special about Carol's is that she uses GlassFish's JPA implementation, not Hibernate. Nothing wrong with Hibernate, of course, but it is good to beat on TopLink to make sure it is up to snuff.
Hopefully, the next version of GlassFish will auto-discover the beans, just like JBoss does.
by venkatesh045 - 2008-01-27 23:21
http://blogs.sun.com/venky/entry/developing_seam_application_with_woodstock Uses seam with woodstock on netbeans.