The Source for Java Technology Collaboration
User: Password:



Carol McDonald

Carol McDonald's Blog

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

Posted by caroljmcdonald on June 04, 2007 at 10:06 AM | Comments (6)




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. 
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:
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->New Project (Ctrl+Shift+N). The New Project dialog box appears.
  • Under Choose Project pane, select Web under Categories and Visual Web Application under Projects, and click Next
            newproject
         
  • 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      

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.

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

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 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 bold) to the code already in SessionBean1. 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. 

Code Sample : SessionBean1
   
private Item item;
private int firstItem = 0;
private int size=0;
private int lastBatchItem=0;
private int batchIndex=0;
private int index=0;
private List items=null;
private int batchSize = 10;
@PersistenceUnit(unitName = "vwp-sessionpaginationPU")
private EntityManagerFactory emf;

private EntityManager getEntityManager() {
return emf.createEntityManager();
}
public Item getItem() {
return item;
}

public void setItem(Item item) {
this.item = item;
}
public Item findItem(String id) {
EntityManager em = getEntityManager();
try{
item = (Item) em.find(Item.class, id);
return item;
} finally {
em.close();
}
}



public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public Item getItem(int index){
items=getItems();
if( index >= firstItem)
batchIndex= index-firstItem;
else if( firstItem < batchSize){
batchIndex= firstItem;
}
if (batchIndex>=batchSize) batchIndex=batchSize-1;
item=items.get(batchIndex);
return item;
}

public List getItems(){
if (items==null || items.isEmpty() ){
items = getItems( firstItem,batchSize);
}
return this.items;
}

public List getNextItems() {
if (size > batchSize) {
items = getItems( firstItem,batchSize);
}
return this.items;
}
public List getItems(int firstItem,int batchSize) {
EntityManager em = getEntityManager();
try{
Query q = em.createQuery("select object(o) from Item as o");
q.setMaxResults(batchSize);
q.setFirstResult(firstItem);
items=q.getResultList();
return items;
} finally {
em.close();
}
}
public int getItemCount() {
EntityManager em = getEntityManager();
try{
int count = ((Long) em.createQuery("select count(o) from Item as o").getSingleResult()).intValue();
return count;
} finally {
em.close();
}
}
public void setItem(int index) {
item=getItem(index);
}
public int getFirstItem() {
index=firstItem;
return firstItem;
}
public void first() {
firstItem=0;
index=firstItem;
getNextItems();
}
public void last() {
firstItem=size-batchSize;
index=size-1;
getNextItems();
}

public int getLastBatchItem() {
lastBatchItem= firstItem + batchSize > size ? size : firstItem + batchSize;
lastBatchItem--;
return lastBatchItem;
}
public int getBatchSize() {
return batchSize;
}
public void nextBatch() {
if (firstItem + batchSize < getItemCount()) {
firstItem += batchSize;
index=firstItem;
getNextItems();
} else{
index=getLastBatchItem();
}
}

public void prevBatch() {
firstItem -= batchSize;
if (firstItem < 0) {
firstItem = 0;
}
index=firstItem;
getNextItems();
}
public void next() {
if (index < size) {
index++;
}
if (index > firstItem + batchSize) {
nextBatch();
}
}

public void prev() {
if (index>0){
index--;
}
if (index < firstItem) {
prevBatch();
}
}



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

Code Sample : SessionBean1 init() method
 
public void init() {
. . .


items=getItems();
size = getItemCount();
if (size < batchSize){
batchSize=size;
}
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.

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


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 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 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 . 

Code Sample : button1_action()
   
public String button1_action() {

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() {

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() {

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() {

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.

Code Sample : prerender()
   
public void prerender() {

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


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.






Bookmark blog post: del.icio.us del.icio.us Digg Digg DZone DZone Furl Furl Reddit Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment

  • This is really useful. Thanks Carol!

    Posted by: leonardogalvao on June 04, 2007 at 04:29 PM

  • Hi Carol, great job :) But in the section: 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:... --item-- doens't appear in the dialog box. Using NB 5.5.1. Suggestions?

    Posted by: max_dev on June 05, 2007 at 11:19 AM

  • You made sure the item attribute is in the Session bean , right? Then try building the project, close and reopen the project. You have to close and reopen a project to make the Session Bean Item appear in the list of Bind to Data Objects.

    Posted by: caroljmcdonald on June 05, 2007 at 12:25 PM

  • Thanks!

    Posted by: caroljmcdonald on June 05, 2007 at 12:26 PM

  • Right-click the project node and choose New > File/Folder.
    From the Persistence category, select Entity Classes from Database and click Next.
    This option does not appear in netbeans5.5 with Visual Web Pack. Can you help me.

    Posted by: dhirendra1007 on August 09, 2007 at 12:54 AM

  • hi, this feature is there for Netbeans 5.5 with VWP. We used this feature in the Java One Hands on lab 4450, and the lab was tested. In the Projects window, right click on your project node, select new file/folder, then select persistence, then select entity classes from database.
    For a complete lab on Java EE & JPA with netbeans try this:
    http://www.javapassion.com/j2ee/#Java_EE_5__EJB_3.0
    Also you can ask netbeans questions here:
    http://www.netbeans.org/community/lists/top.html

    Posted by: caroljmcdonald on August 10, 2007 at 08:55 AM





Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds