Skip to main content

Sample Store Catalog Application using Visual Web Pack and the Java Persistence APIs

Posted by caroljmcdonald on June 4, 2007 at 10:06 AM PDT





This Sample Store Catalog app demonstrates the usage of Visual Web Pack
and the new Java Persistence APIs  to implement pagination in a
Web application.

Below are step by step instructions on how to build this  example
on your own. 

href="http://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555">download
sample code

If you would like to learn more about building a sample store
application using Visual Web Pack, try out this JavaOne HOL:

href="http://developers.sun.com/learning/javaoneonline/j1lab.jsp?lab=LAB-4450&yr=2007&track=8">Building
a Real Life Application With Ajax and JavaServer Faces Components using
the NetBeans Visual Web Pack




Creating a new
Project




From NetBeans IDE, Create a new Visual Web Pack NetBeans project:

  • Select File-> style="font-weight: bold;">New Project (Ctrl+Shift+N). The style="font-weight: bold;">New Project dialog box appears.
  • Under Choose Project
    pane,
    select Web under style="font-weight: bold;">Categories and style="font-weight: bold;">Visual Web Application
    under Projects, and click style="font-weight: bold;">Next

           
newproject src="http://weblogs.java.net/blog/caroljmcdonald/archive/newproject.PNG">

         

  • the Name and
    Location

    pane appears.
  • Enter the  project name vwp-sessionpagination.

  • For the Project Location
    field, browse to select where you want to put your project.
  • Click Finish style="font-weight: bold;">      
style="font-family: helvetica,arial,sans-serif;">

Adding
scrolling to the application using the  Java Persistence APIs

The steps below explain how to

  • access a
    database with the Java Persistence API.
  • develop a JSP page which uses a Property Sheet
    component
  • bind data
    objects to JavaServer Faces components to
    dynamically show the details of the catalog  item on the page.
style="font-family: helvetica,arial,sans-serif;"> style="font-weight: bold; color: rgb(0, 0, 0); text-decoration: underline;">


style="font-weight: bold;">Creating the Database tables

Choose Tools > Java DB Database > Start
Java DB
Server.
You'll see in the Output window  indicating the server has been
started.





Unzip the dowloaded  source code example. Copy the directory
vwp-sessionpagination\setup (and
all of its contents)  from the
example into your project directory (the build.xml uses your project's
netbeans properties files). From a command line
window cd
into the directory yourprojectname\setup.  
Then on the
command
line type:  ant create-db.  This will create the database
tables.  The
text file with the SQL is in the directory:
vwp-sessionpagination\setup\sql\javadb .



Creating
the
Entity Classes and Persistence Unit


Create the JPA entity
classes from the  data base tables.





Right-click the  project node and choose New
>
File/Folder
.

From the Persistence category, select Entity Classes
from
Database
and click Next.

In the Data Source drop-down, select the jdbc/PETCatalogDB
database. If
prompted for a user name and password, use app and app. Select the
ITEM

table from the list, click Add and
then click Next.

newentity src="http://weblogs.java.net/blog/caroljmcdonald/archive/newentity2.jpg">




Leave the tables and class names as their default, and set
the package
to model .



newentity



Click the Create Persistence Unit button. You can
leave the default the persistence unit name (Remember this name, it
will be used later to get the EntityManagerFactory) . If you installed
another persistence
provider you can select that, otherwise use TopLink. Select style="font-weight: bold;">None
as the table generation strategy. Click
Create.



createpu

Click Finish in the Entity
Classes from
Database wizard. The IDE
creates the persistence unit (persistence.xml in the
projectname\src\conf directory) and the entity
classes (in Source Packages ).

In the Projects window expand Source Packages > data to
look at the
Item.java Entity Class which was
generated from the item table.


Adding
code
to the Session Bean to get a list of items

In the Projects window,Double-click the
SessionBean1 node
to open
the SessionBean1.java source file in the editor. Add the following code
(shown in style="font-weight: bold;">bold)
to the code already in SessionBean1. style="color: rgb(255, 0, 0);">Make sure the
PersistenceUnit unitName (shown in Red below) is the same name you used
when
creating the Persistence Unit above. This is JPA code to get and
page through a  list of Items which
we will use for
scrolling through the catalog.This JPA code calls the EntityManager
createQuery and Query
getResultList methods to get a list of items and stores the results in
the SessionBean1 items property. The next(), prev()... methods will be
used by the page  button action methods to scroll through
the items list. 


cellspacing="0">
Code Sample : SessionBean1
   
    private Item item; style="font-weight: bold;">    private int firstItem = 0; style="font-weight: bold;">    private int size=0; style="font-weight: bold;">    private int lastBatchItem=0; style="font-weight: bold;">    private int batchIndex=0; style="font-weight: bold;">    private int index=0; style="font-weight: bold;">    private List items=null; style="font-weight: bold;">    private int batchSize = 10; style="font-weight: bold;">    @PersistenceUnit(unitName = " style="color: rgb(255, 0, 0);">vwp-sessionpaginationPU") style="font-weight: bold;">    private EntityManagerFactory emf; style="font-weight: bold;">    style="font-weight: bold;">    private EntityManager getEntityManager() { style="font-weight: bold;">        return emf.createEntityManager(); style="font-weight: bold;">    } style="font-weight: bold;">    public Item getItem() { style="font-weight: bold;">        return item; style="font-weight: bold;">    } style="font-weight: bold;">    style="font-weight: bold;">    public void setItem(Item item) { style="font-weight: bold;">        this.item = item; style="font-weight: bold;">    } style="font-weight: bold;">    public Item findItem(String id) { style="font-weight: bold;">        EntityManager em = getEntityManager(); style="font-weight: bold;">        try{ style="font-weight: bold;">            item = (Item) em.find(Item.class, id); style="font-weight: bold;">            return item; style="font-weight: bold;">        } finally { style="font-weight: bold;">            em.close(); style="font-weight: bold;">        } style="font-weight: bold;">    } style="font-weight: bold;">    style="font-weight: bold;">
style="font-weight: bold;">    public int getIndex() { style="font-weight: bold;">        return this.index; style="font-weight: bold;">    } style="font-weight: bold;">    public void setIndex(int index) { style="font-weight: bold;">        this.index = index; style="font-weight: bold;">    } style="font-weight: bold;">    public Item getItem(int index){ style="font-weight: bold;">        items=getItems(); style="font-weight: bold;">        if( index >= firstItem) style="font-weight: bold;">            batchIndex= index-firstItem; style="font-weight: bold;">        else if( firstItem < batchSize){ style="font-weight: bold;">            batchIndex= firstItem; style="font-weight: bold;">        } style="font-weight: bold;">        if (batchIndex>=batchSize) batchIndex=batchSize-1; style="font-weight: bold;">        item=items.get(batchIndex); style="font-weight: bold;">        return item; style="font-weight: bold;">    } style="font-weight: bold;">   
    style="font-weight: bold;">public List getItems(){ style="font-weight: bold;">        if (items==null || items.isEmpty() ){ style="font-weight: bold;">            items = getItems( firstItem,batchSize); style="font-weight: bold;">        } style="font-weight: bold;">        return this.items; style="font-weight: bold;">    } style="font-weight: bold;">    style="font-weight: bold;">    public List getNextItems() { style="font-weight: bold;">        if (size > batchSize) { style="font-weight: bold;">            items = getItems( firstItem,batchSize); style="font-weight: bold;">        } style="font-weight: bold;">        return this.items; style="font-weight: bold;">    } style="font-weight: bold;">    public List  getItems(int firstItem,int batchSize) { style="font-weight: bold;">        EntityManager em = getEntityManager(); style="font-weight: bold;">        try{ style="font-weight: bold;">            Query q = em.createQuery("select object(o) from Item as o"); style="font-weight: bold;">            q.setMaxResults(batchSize); style="font-weight: bold;">            q.setFirstResult(firstItem); style="font-weight: bold;">            items=q.getResultList(); style="font-weight: bold;">            return items; style="font-weight: bold;">        } finally { style="font-weight: bold;">            em.close(); style="font-weight: bold;">        } style="font-weight: bold;">    } style="font-weight: bold;">    public int getItemCount() { style="font-weight: bold;">        EntityManager em = getEntityManager(); style="font-weight: bold;">        try{ style="font-weight: bold;">            int count = ((Long) em.createQuery("select count(o) from Item as o").getSingleResult()).intValue(); style="font-weight: bold;">            return count; style="font-weight: bold;">        } finally { style="font-weight: bold;">            em.close(); style="font-weight: bold;">        } style="font-weight: bold;">    } style="font-weight: bold;">    public void setItem(int index) { style="font-weight: bold;">        item=getItem(index); style="font-weight: bold;">    } style="font-weight: bold;">    public int getFirstItem() { style="font-weight: bold;">        index=firstItem; style="font-weight: bold;">        return firstItem; style="font-weight: bold;">    } style="font-weight: bold;">    public void first() { style="font-weight: bold;">        firstItem=0; style="font-weight: bold;">        index=firstItem; style="font-weight: bold;">        getNextItems(); style="font-weight: bold;">    } style="font-weight: bold;">    public void last() { style="font-weight: bold;">        firstItem=size-batchSize; style="font-weight: bold;">        index=size-1; style="font-weight: bold;">        getNextItems(); style="font-weight: bold;">    } style="font-weight: bold;">    style="font-weight: bold;">    public int getLastBatchItem() { style="font-weight: bold;">        lastBatchItem= firstItem + batchSize > size ? size : firstItem + batchSize; style="font-weight: bold;">        lastBatchItem--; style="font-weight: bold;">        return lastBatchItem; style="font-weight: bold;">    } style="font-weight: bold;">    public int getBatchSize() { style="font-weight: bold;">        return batchSize; style="font-weight: bold;">    } style="font-weight: bold;">    public void nextBatch() { style="font-weight: bold;">        if (firstItem + batchSize < getItemCount()) { style="font-weight: bold;">            firstItem += batchSize; style="font-weight: bold;">            index=firstItem; style="font-weight: bold;">            getNextItems(); style="font-weight: bold;">        } else{ style="font-weight: bold;">            index=getLastBatchItem(); style="font-weight: bold;">        } style="font-weight: bold;">    } style="font-weight: bold;">    style="font-weight: bold;">    public void prevBatch() { style="font-weight: bold;">        firstItem -= batchSize; style="font-weight: bold;">        if (firstItem < 0) { style="font-weight: bold;">            firstItem = 0; style="font-weight: bold;">        } style="font-weight: bold;">        index=firstItem; style="font-weight: bold;">        getNextItems(); style="font-weight: bold;">    }
style="font-weight: bold;">    public void next() { style="font-weight: bold;">        if (index < size) { style="font-weight: bold;">            index++; style="font-weight: bold;">        } style="font-weight: bold;">        if (index > firstItem + batchSize) { style="font-weight: bold;">            nextBatch(); style="font-weight: bold;">        } style="font-weight: bold;">    } style="font-weight: bold;">    style="font-weight: bold;">    public void prev() { style="font-weight: bold;">        if (index>0){ style="font-weight: bold;">            index--; style="font-weight: bold;">        } style="font-weight: bold;">        if (index < firstItem) { style="font-weight: bold;">            prevBatch(); style="font-weight: bold;">        } style="font-weight: bold;">    }





         Add the following code
in bold to the SessionBean1 init() method :


cellspacing="0">
Code Sample : SessionBean1 init() method
 
public void init() {
  . . .

 
style="font-weight: bold;">       items=getItems(); style="font-weight: bold;">       size = getItemCount(); style="font-weight: bold;">       if (size < batchSize){ style="font-weight: bold;">           batchSize=size; style="font-weight: bold;">       } style="font-weight: bold;">       setItem(firstItem);

  }
     



Right-click in the source and choose Fix
Imports from the
pop-up
menu.



The Fix Imports dialog appears.



Select the following fully qualified
names, and click OK.



cellspacing="0">
Class Name Fully Qualified Name
Query javax.persistence.Query
List java.util.List


Close and save the file.

Close and reopen the project.

You must close and reopen the project to make the Session Bean Item
appear in the list of Bind
to Data Objects, which we will do later with the Property components.




Add a
property
sheet and Properties to the Page1

style="font-weight: bold;">

In the Projects window, double-click Web Pages
> Page1.jsp
to open the page in the Visual Designer.

From the Layout section of the Palette,
drag a Property
Sheet
component onto the page.

The Property Sheet component provides a
container for laying out the catalog item information. The Property
Sheet component contains a Property
Sheet Section, which in turn contains a Property component.

Select Property Sheet Section 1. In the Properties
window, set the label property to style="font-weight: bold;">Pet Catalog

. 



propertysheetsection.jpg

 


In the Outline window, expand
propertySheet1 >
section1 and then select the property1 node. In the Properties window,
set the label
property to Scroll:
and press Enter.

In the Outline window, select section1, right-click, and
choose
Add Property from the pop-up menu. In the Properties window, set the label
property to Name:

In the Outline window, select section1, right-click, and
choose
Add Property from the pop-up menu. In the Properties window, set the label
property to Description:

In the Outline window, select section1, right-click, and
choose
Add Property from the pop-up menu. In the Properties window, set the label
property to Price: and press Enter.

In the Outline window, select section1, right-click, and
choose
Add Property from the pop-up menu. In the Properties window, set the label
property to Photo: and press Enter.
 

Your Page1 page should now look like the figure below:



propertysheet.jpg


Drag a Button component from the
Palette and drop
it on
the property1 node in the Outline window.

The Button becomes a subnode of
property1. The Button also appears in
the Visual Designer. In the Button properties window (or on the button
itself) type << for the text property .

 

Drag another Button component
from the Palette and
drop
it on the property1 node in the Outline window.

In the Button properties window type
<
for the
text
property .

Drag another Button component
from the Palette and
drop
it on the property1 node in the Outline window.

In the Button properties window type
>
for the
text
property .

Drag another Button component
from the Palette and
drop
it on the property1 node in the Outline window.

In the Button properties window type >>
for the
text
property.

Your Page1 page should now look like the figure below.


buttons



Drag a Static Text component from
the Palette and
drop
it on the property2 node in the Outline window.

The Static Text becomes a subnode of
property2. The Static Text also
appears in the Visual Designer. In the static text properties window
set the id property to name .

propertyname

Right-click the Static Text component and
choose Bind to
Data
from the pop-up menu.

In the dialog box, In the Bind to
an Object
tab,
expand SessionBean1,
expand item, select property itemname and click OK.

This will set the label text property to #{SessionBean1.item.itemname}
, as shown in the figure below:






For the Description and Price properties repeat the steps
above
to drag a static text component onto the associated property, then bind
to the associated SessionBean1 item properties:
#{SessionBean1.item.description}, #{SessionBean1.item.price}





For the Photo property drag an Image component
from the
Palette and drop it on the property4 node in the Outline window. In the
image Properties Window enter photoid
property, enter 150 for the width property, enter 150
for the height property.


Right-click the Image component and
choose Bind to Data
from the pop-up menu.

In the dialog box, In the Bind to
an Object
tab,
expand
SessionBean1, expand item, select property imageurl and click
OK.

This will set the image url property to #{SessionBean1.item.imageurl}.


Go to the Page1 in the style="font-weight: bold;">Visual Designer.





Your Page1 should now look like the figure below (I added a image of a
parrot and a Label "Java Pet Store"  to the page below):









Add
Actions
to the scrolling buttons on Page1:



In the Projects window, double-click Web Pages
>Page1.jsp
to open the page in the Visual Designer.



Double-click the << button component that you just
added
to
the page.



The IDE adds a button1_action() method for processing a click on the
button and displays the button1_action() method in the source editor.
The IDE also registers the method as a handler for the action event.
Next you add code to this method.




Add the following code (shown in bold)
to the
button1_action() method. This code calls the SessionBean1.prevBatch()
method to query to get the previous batch (resultList) of items (based
on the batchSize query variable)  from the item table.  The
items table in this sample is not very large, but for large databases
it is useful to set a size for the query result list . 

border="1" cellpadding="2" cellspacing="0">
Code Sample : button1_action()
   
  public String button1_action() {
    style="font-weight: bold;">
       style="color: rgb(0, 0, 153);">getSessionBean1().prevBatch();
   
       return null;
    }

 



Double-click on the < button to
open the
button2_action()
method in the Java editor.

Add the following code (shown in bold)
to the
button2_action() method. This code calls the SessionBean1.prev() method
to decrement the item list index . 

Code Sample : button2_action()
   
  public String button2_action() {
    style="font-weight: bold;">
      style="color: rgb(0, 0, 153);">getSessionBean1().prev();
   
      return null;
    }

 





Double-click on the > button to open the
button3_action()
method in the Java editor.

Add the following code (shown in bold)
to the
button3_action() method. This code calls the SessionBean1.next() method
to  increment the item list index . 

Code Sample : button3_action()
   
  public String button3_action() {
    style="font-weight: bold;">
         style="color: rgb(0, 0, 153);">getSessionBean1().next();
   
      return null;
    }

 





Double-click on the >> button to open the
button4_action()
method in the Java editor.

Add the following code (shown in bold)
to the
button4_action() method. This code calls the SessionBean1.nextBatch()
method to query to get the next batch (resultList) of items (based on
the batchSize query variable)  from
the item table. 

Code Sample : button4_action()
   
  public String button4_action() {
    style="font-weight: bold;">
       style="color: rgb(0, 0, 153);"> getSessionBean1().nextBatch();
   
        return null;
    }

 



In the Java Editor for the Page1
page, scroll
up to
the prerender() method. Add the following code
(shown in bold) to the
prerender() method.

border="1" cellpadding="2" cellspacing="0">
Code Sample : prerender()
   
public void prerender() {
    style="font-weight: bold;">
getSessionBean1().setItem(getSessionBean1().getIndex());
   
    }

 



 





Run
the
project to test scrolling through the Page1 Pages using
Hibernate with the Java Persistence API


Now you are ready to build and run the project.


In the main toolbar, click Run Main
Project to run the
project.
The detailed item information for the 1st item from the ITEM database
table should be
displayed. Click on the << (Previous Batch), < (Previous),
> (Next), and >> (Next Batch)
buttons
to
scroll through the items, from the ITEM database table, displayed on
the  page.






runapp.jpg src="http://weblogs.java.net/blog/caroljmcdonald/archive/runapp.jpg"
height="712" width="723">




Summary:

We  went over  how to develop a quick application that
accesses a database with the Java Persistence API
and how to configure and use the Property Sheet, Property, Static Text,
and Button components in NetBeans Visual Web Pack
to display and scroll through dynamic data from the database.







Related Topics >>