Skip to main content

Java EE 6 Pet Catalog with GlassFish v3 preview and MySQL

Posted by caroljmcdonald on August 11, 2009 at 11:49 AM PDT

This Pet Catalog app explains a web application that
uses JSF 2.0, Java EE 6, GlassFish and MySQL. I took this
example  GlassFish
and MySQL, Part 2: Building a CRUD Web Application With Data Persistence
and modified it to use some of the new features of JSF 2.0 and Java EE
6.

Explanation of the usage of JSF 2.0 and Java EE 6 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.


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


JSF 2.0 Facelets XHTML instead of JSP

For JSF 2.0, Facelets XHTML is the preferred way to declare JSF Web
Pages. JSP is supported for backwards compatibility, but not all JSF
2.0 features will be available for views using JSP as their page
declaration language.  JSF 2.0 Facelets has some nice features
like templating (similar in functionality to Tiles) and composite
components, which I'm not going to discuss here but you can read about
that in this article: http://www.ibm.com/developerworks/java/library/j-jsf2fu2/index.html and in this Tech Tip Composite
UI Components in JSF 2.0.






The Catalog application's resources




JSF 2.0 standardizes how to define web resources. Resources are any
artifacts that a component may need in order to be rendered properly --
images, CSS, or JavaScript files.  With JSF 2.0 you put resources
in a resources
directory or a subdirectory.

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



In your Facelets pages, you can access css files with the 
,  javascript files with the
, and images with the JSF
tags. The list.xhtml uses the 

style="color: rgb(204, 0, 0); font-weight: bold;"> 
tag to load the styles.css stylesheet
, and the tag to display images from the resources as
shown below:


Code Sample from:  list.xhtml



       
style="color: rgb(204, 0, 0); font-weight: bold;"> name="css/styles.css" target="body"/>

       

        library="images" name="banner_logo.gif"  />   


       

       





The Catalog application uses a resource bundle to contain the static
text and
error messages used by the Facelets pages. Putting messages in a
resource bundle makes it easier to modify and internationalize your
Application text.  The messages are in a properties file in a java
package directory.


Code Sample from:  messages.properties 

style="color: rgb(204, 0, 0); font-weight: bold;">

       
Title=Pet Catalog

Next=Next

Previous=Prev

Name=Name

 


       





The resource bundle is configured in the faces-config.xml File (you
don't need any other
configuration in the faces-config.xml for JSF 2.0, as explained later
you no longer have to configure managed beans and navigation with XML).




Code Sample from:  faces-config.xml

style="color: rgb(204, 0, 0); font-weight: bold;">

       


    <resource-bundle>

       
web.WebMessages

        style="color: rgb(0, 102, 0); font-weight: bold;">msgs

   



 


       







The List.xhtml facelets page uses a JSF dataTable component to display a list of
catalog items in an html table.  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.xhtml web page the dataTable is defined as shown
below: 
(Note: Red colors
are for Java EE tags, annotations code, 
and Green is
for my code or variables)


Code Sample from:  list.xhtml



       
<style="font-weight: bold; color: rgb(204, 0, 0);">h:dataTablestyle="color: rgb(204, 0, 0);"> style="font-weight: bold; color: rgb(204, 0, 0);">value='style="font-weight: bold;">#{catalog.style="color: rgb(0, 102, 0); font-weight: bold;">itemsstyle="font-weight: bold;">}' style="font-weight: bold; color: rgb(204, 0, 0);">var='style="color: rgb(0, 102, 0); font-weight: bold;">style="font-family: monospace;">row'
        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

style="color: rgb(0, 102, 0); font-weight: bold;">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 
style="font-weight: bold; color: rgb(204, 0, 0);" class="cCode">dataTable
component
 iterates through the list, each reference to style="color: rgb(0, 102, 0); font-weight: bold;">dataTableItem
 points to the current item in the
list.



JSF 2.0 Annotations instead of XML configuration


The dataTable's class="cCode">value
is bound to the
style="color: rgb(0, 102, 0); font-weight: bold;">items
property
of the
style="color: rgb(0, 102, 0);">catalog
managed
bean. With JSF 2.0 managed beans do not have to be configured in the
faces-config.xml file, you annotate the managed beans instead as shown
below:


Code Sample from:
style="font-weight: bold; color: rgb(0, 102, 0);">Catalog
style="font-weight: bold;">.java


       

        @ManagedBeanstyle="color: rgb(204, 0, 0); font-weight: bold;">
        @SessionScoped

        public class Catalog implements Serializable {

       

       


       


       

       

By convention, the name of a managed bean is the same as the class
name, with the first letter of the class name in lowercase. To specify
a managed bean name you can use the name attribute of the ManagedBean
annotation, like this: @ManagedBean(name = "Catalog").





This Catalog style="font-weight: bold;"> ManagedBean

style="color: rgb(0, 102, 0); font-weight: bold;">items
property is defined as shown below:


Code Sample from:
style="font-weight: bold; color: rgb(0, 102, 0);">Catalog
style="font-weight: bold;">.java


    private
List items = null;



    public List getItems() {

        if (items == null) {

           
getPagingInfo();

           
items = getNextItems(pagingInfo.getBatchSize(),
pagingInfo.getFirstItem());

        }

        return items;

    }

   



       

       





The style="color: rgb(0, 102, 0); font-weight: bold;">getItems()
method returns a List of item objects

.
The JSF class="cCode">dataTable
,
supports data binding to a
collection of data objects.  The dataTable object 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
style="color: rgb(0, 102, 0);">name
, imagethumburl,
and price  
style="color: rgb(0, 102, 0); font-weight: bold;">
are
displayed with the
style="color: rgb(204, 0, 0); font-weight: bold;">column
component:


Code Sample from: list.xhtml



        <style="color: rgb(204, 0, 0); font-weight: bold;">h:dataTablestyle="font-weight: bold;"> var="style="color: rgb(0, 102, 0); font-weight: bold;">rowstyle="font-weight: bold;">" value="#{style="color: rgb(0, 102, 0);">catalog.items}">style="font-weight: bold;">
       
  <style="color: rgb(204, 0, 0);">h:column>

              <f:facet name="header">

                  <style="color: rgb(204, 0, 0);">h:outputText style="color: rgb(204, 0, 0);">value="#{msgs.Name}"/>

             

              <h:commandLink action="#{catalog.showDetail(style="color: rgb(0, 102, 0);">row)}" value="#{style="color: rgb(0, 102, 0);">row.name}" />

         
       
   

          <h:column>

              <f:facet name="header">

                  <style="color: rgb(204, 0, 0);">h:outputText style="color: rgb(204, 0, 0);">value="#{msgs.Photo}"/>

             

             
style="color: rgb(204, 0, 0);"> library="images" name="#{row.imagethumburl}"/>


         
       


          <style="color: rgb(204, 0, 0); font-weight: bold;">h:columnstyle="font-weight: bold;">>

             
        <
f:facetstyle="font-weight: bold;"> name="style="color: rgb(204, 0, 0); font-weight: bold;">headerstyle="font-weight: bold;">">

                 
        <
h:outputTextstyle="font-weight: bold;"> style="color: rgb(204, 0, 0); font-weight: bold;">valuestyle="font-weight: bold;">="#{msgs.Price}"/>style="font-weight: bold;">
             
       


             
        <
h:outputTexstyle="font-weight: bold;">t style="color: rgb(204, 0, 0); font-weight: bold;">valuestyle="font-weight: bold;">="#{style="color: rgb(0, 102, 0); font-weight: bold;">row.pricestyle="font-weight: bold;">}"/>

         
       


       

       

       



The column tags represent columns of data in a dataTable component. While
the dataTable component is iterating over the rows of
data, it processes
the UIColumn component associated with each

style="color: rgb(204, 0, 0); font-weight: bold;">column
tag for each row in
the table.



The dataTable component  iterates through the
list
of items
(
style="font-weight: bold;">style="color: rgb(0, 102, 0); font-weight: bold;">catalog.items

and displays the 
style="font-weight: bold;">
item (
style="font-weight: bold;">var="style="color: rgb(0, 102, 0); font-weight: bold;">rowstyle="font-weight: bold;">") 
attribute
style="color: rgb(204, 0, 0); font-weight: bold;">value. 
Each
time UIData iterates through the list of items, it renders one cell in
each column.



The dataTable and column tags use
style="color: rgb(204, 0, 0); font-weight: bold;">facet
to represent parts of the
table that are not repeated or updated. These include
style="color: rgb(204, 0, 0); font-weight: bold;">header
s,
footers,
and captions.


Java EE 6: JSF 2.0,  EJB 3.1, and Java Persistence API
(JPA)  2.0

The Catalog style="font-weight: bold;"> ManagedBean annotates the field

private
ItemFacade itemFacade;
 
with @EJB , which causes an
style="color: rgb(0, 102, 0); font-weight: bold;">itemFacade
EJB to be
injected when the managed bean is instatiated. The
style="font-weight: bold; color: rgb(0, 102, 0);"> Catalog
style="color: rgb(0, 102, 0); font-weight: bold;">getNextItems 
method
calls the ItemFacade Stateless EJB which uses the Java
Persistence API EntityManager
Query
object to return a list of items.


 




 
   
     
   
   
     
Code Sample from: Catalog.java


       
style="color: rgb(204, 0, 0); font-weight: bold;">@ManagedBeanstyle="color: rgb(204, 0, 0); font-weight: bold;">
        @SessionScoped

        public class Catalog implements Serializable {


    

            style="color: rgb(204, 0, 0); font-weight: bold;">@EJB

            private ItemFacade style="color: rgb(0, 102, 0); font-weight: bold;">itemFacade;

       

            public List  style="color: rgb(0, 102, 0); font-weight: bold;">getNextItems(int
        maxResults, int firstResult) { 

              
        return itemFacade.findRange(maxResults,
        firstResult);    

           }

           

       



style="font-weight: bold;">EJB 3.1 No-interface local client View



With EJB 3.1, local EJBs  do not  have to a implement
separate interface, that is, all public methods of the bean class are
automatically exposed to the caller.



href="http://blogs.sun.com/enterprisetechtips/entry/a_sampling_of_ejb_3">Simplified
Packaging




With Java EE 6, EJBs can be directly packaged in a WAR file just like
web components.

 

The ItemFacade
EJB uses the Java
Persistence API EntityManager
Query
object to return a list of items. The
style="color: rgb(0, 102, 0); font-weight: bold;">ItemFacade
EJB annotates the field private EntityManager em; 
with
style="font-weight: bold;">@PersistenceContext
, which causes an entity manager to be
injected when it is instatiated.


Code Sample from: ItemFacade.java
 

       
style="color: rgb(204, 0, 0); font-weight: bold;">@Statelessstyle="color: rgb(204, 0, 0); font-weight: bold;">

        public class ItemFacade {


    

            style="color: rgb(204, 0, 0); font-weight: bold;">@PersistenceContext(unitName
        = "catalogPU")

            private style="color: rgb(153, 0, 0); font-weight: bold;">EntityManager em;

       

            public List findRange(int maxResults,
        int firstResult) {

                style="color: rgb(204, 0, 0); font-weight: bold;">Query q =
        em.createQuery("select object(o) from Item as o");

                q.setMaxResults(maxResults);

               
        q.setFirstResult(firstResult);

                return q.getResultList();

            }

           

       


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.style="color: rgb(204, 0, 0); font-weight: bold;">setMaxResults
(int maxResult)
sets the maximum number of results to retrieve. style="font-family: mon;">
q.style="color: rgb(204, 0, 0); font-weight: bold;">setFirstResult
(int startPosition)
sets the position of the first result to retrieve.

In the code below, we show the

style="color: rgb(0, 102, 0); font-weight: bold;">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:

  1. annotating the class with an style="color: rgb(204, 0, 0); font-weight: bold;">@Entity annotation.
  2. annotating   the primary key identifier with style="color: rgb(204, 0, 0); font-weight: bold;">@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

style="color: rgb(0, 102, 0); font-weight: bold;">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
style="color: rgb(204, 0, 0); font-weight: bold;">   

            private Integer id;


            private String name;   

            private String description;   

            private String imageurl;   

            private String imagethumburl; 

            private BigDecimal price;

            style="color: rgb(204, 0, 0); font-weight: bold;">@ManyToOnestyle="color: rgb(204, 0, 0);">

            private style="color: rgb(0, 102, 0); font-weight: bold;">Address address;

       
    style="color: rgb(204, 0, 0); font-weight: bold;">@ManyToOne

            private style="color: rgb(0, 102, 0); font-weight: bold;">Product product;


     

            public Item() { }

            


    public String getName() {

               
        return name;

            }


            public void setName(String name) {

               
        this.name = name;

            }
    

       


            ...

        }   

       

       







The Catalog ManagedBean pages through the list of

style="color: rgb(0, 102, 0); font-weight: bold;">Item
s
by
maintaining the PagingInfo.firstItem and PagingInfo.batchSize
attributes and passing these as
parameters to the 
style="color: rgb(0, 102, 0); font-weight: bold;">
style="color: rgb(0, 102, 0); font-weight: bold;">getNextItems
(firstItem,
batchSize) method.
The catalog's
scope  is
defined with the annotation
style="color: rgb(204, 0, 0); font-weight: bold;">@SessionScoped
,
a JSF Managedbean
with session scope will be stored in the session meaning that the
bean's properties will stay alive for the life of the Http Session.





A JSF commandButton is  used to provide a button to click on to
display the next page of items.  The
style="color: rgb(204, 0, 0); font-weight: bold;">commandButton
tag is used to submit an style="color: rgb(204, 0, 0); font-weight: bold;">action event to the application. 


Code Sample from: list.xhtml


          action="#{style="font-family: mon;">style="color: rgb(0, 102, 0); font-weight: bold;">catalog.next}"
        value="#{msgs.Next}" />   

       



This

style="color: rgb(204, 0, 0); font-weight: bold;">commandButton action 
attribute
references the
style="color: rgb(0, 102, 0); font-weight: bold;">catalog
Managed bean
style="color: rgb(0, 102, 0); font-weight: bold;">next
()
method which calculates
the
next page's first row number  and returns a logical outcome
String, which causes the style="color: rgb(0, 102, 0); font-weight: bold;">list.xhtml
page
to display the next page's
list .
The catalog next method is defined as shown below:


Code Sample from:
style="font-weight: bold; color: rgb(0, 102, 0);">catalog
.java


   public String style="color: rgb(0, 102, 0); font-weight: bold;">next() {

               if (firstItem + batchSize
        < itemCount()) {

                  
        firstItem += batchSize;

               }

               return "style="color: rgb(0, 102, 0); font-weight: bold;">list";

           }

       


JSF 2.0 Simplified Navigation



The JavaServer Faces style="color: rgb(204, 0, 0); font-weight: bold;"> 2.0  NavigationHandler convention adds .xhtml to the logical outcome of the action method (in
this example list)
and
loads that file, in this case, it loads the list.xhtml page after this method returns. If the action doesn't begin with a
forward slash (/), JSF assumes that it's a relative path.  You can
specify an absolute path by adding the slash like this "/items/list".





A JSF commandLink is  used to provide a link to click on to
display a page with the

style="color: rgb(0, 102, 0);">item
details. This 
style="color: rgb(204, 0, 0);">commandLink
action
attribute 
references The
style="color: rgb(0, 102, 0); font-weight: bold;">catalog
style="color: rgb(0, 102, 0); font-weight: bold;">showDetail()
method:


Code Sample from: list.xhtml


          

              

                          value="Name"/>

              


               style="color: rgb(204, 0, 0); font-weight: bold;">commandLink action="#{style="color: rgb(0, 102, 0); font-weight: bold;">catalog.style="color: rgb(0, 102, 0); font-weight: bold;">showDetail(row)}"
        value="#{row.name}"/>   

          


       



href="http://weblogs.java.net/blog/cayhorstmann/archive/2009/07/say_sayonara_to_1.html">With
JSF 2.0 you can now specify parameters in method expressions.
The

style="font-weight: bold; color: rgb(204, 0, 0);">dataTablestyle="color: rgb(204, 0, 0);">
 
style="color: rgb(0, 102, 0); font-weight: bold;">row
object associated with the selected
style="color: rgb(204, 0, 0); font-weight: bold;">
link
is passed as a parameter in the  
style="color: rgb(204, 0, 0); font-weight: bold;">
"#{style="color: rgb(0, 102, 0); font-weight: bold;">catalog.style="color: rgb(0, 102, 0); font-weight: bold;">showDetail(row)}"
 method
expression.

The Catalog
  showDetail() method  gets the
style="color: rgb(0, 102, 0); font-weight: bold;">item
data from the
input parameter,
and returns a string which causes the style="color: rgb(0, 102, 0); font-weight: bold;">detail.xhtml
page to display
the item details :


Code Sample from:
style="font-weight: bold; color: rgb(0, 102, 0);">Catalog
.java


            public String style="color: rgb(0, 102, 0); font-weight: bold;">showDetail(Item
        item)
        {

                this.item = item;

                return "detail";

            }

       



The JavaServer Faces NavigationHandler adds .xhtml to the logical outcome of the action,

style="color: rgb(0, 102, 0); font-weight: bold;">detail
 and loads
that file. In this case, the
JavaServer Faces implementation loads the style="font-weight: bold;">detail.xhtml
page after this method returns.



The detail.xhtml uses the
style="color: rgb(204, 0, 0); font-weight: bold;">outputText
component to display the
style="font-weight: bold; color: rgb(0, 102, 0);">catalog
ManagedBean's
style="font-weight: bold; color: rgb(0, 102, 0);">item
properties:


Code Sample from: detail.xhtml
 

           
        outputText value="#{catalog.item.name}"
        title="Name" />

           
                title="Description"/>

                    name="#{catalog.item.imageurl}" title="Imageurl" />


           
        catalog
.item.price}"
        title="Price" />

           
        catalog
.item.address.city}"
        title="Address" />

           
        catalog
.item.contactinfo.email}"
        title="Address"/>
         




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




GlassFish
v3 is a lightweight server

  • OSGi-based; Embedded API; RESTful admin API; Lightweight and fast
    startup;
  • iterative development cycle "edit-save-refresh browser":
    • Incremental compile of all JSF 2.0 artifacts when you save.
    • Auto-deploy of all web or Java EE 6 artifacts
  • Session retention: maintain sessions across
    re-deployments





Conclusion

This concludes the sample application which demonstrates a pet catalog
web application which uses Java EE 6, GlassFish v3 and MySQL style="color: rgb(0, 0, 153); font-weight: bold;">.


Running the Sample Application

  1. Download and install  style="text-decoration: underline;">NetBeans IDE 6.8 M1
    with GlassFish v3 b57
    (Glassfish v3 preview is Java EE 6
    Preview) , and MySQL
    Community
    Server
    .
  2. Follow these instructions to set up a  jdbc-driver
    for MySQL
    . (Normally this is already setup with Glassfish, but I
    got an errror message with Glassfish v3 b57 that it was missing)
  3. Download
    the sample code.
    Unzip the catalog.zip
    file which you downloaded, this will create a catalog directory with
    the project code.

Create the Pet Catalog database

In order to run the sample code you first have to create the Pet
Catalog database
and fill in  the Item table.


  1. Start NetBeans IDE
  2. Ensure that GlassFish is registered in the NetBeans IDE, as
    follows:

    • Click the Services tab in the NetBeans IDE.
    • Expand the Servers node. You should see GlassFish v2 in
      the list of servers. If not,
      register GlassFish v2 as follows:

      • Right-click the Servers node and select Add Server.
        This opens an Add Server Instance wizard.
      • Select GlassFish v2 in the server list of the
        wizard
        and click the Next button.
      • Enter the location information for the server and
        click
        the Next button.
      • Enter the admin name and password and click the
        Finish
        button.
  3. Start the MySQL or Java DB database as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the databases node. You should see the Java DB
      database in the list of databases. If you have installed the MySQL
      server database, you should also see the MySQL database in the list of
      databases.. Note:  Java DB 
      comes bundled with Netbeans, you can  download MySQL separately.

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/databases.jpg"
      style="width: 320px; height: 104px;">
    • Right-mouse click on the Java DB or MySQL server
      database
      and select Start.
  4. If you installed MySQL, set the properties of the MySQL
    server database as follows:

    • Right-click on the MySQL server database and select
      Properties. This opens the MySQL Server Properties dialog box, as shown
      in Figure 8.

       

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/ServerProps.jpg"
      alt="MySQL Server Basic Properties"
      style="border: 0px solid ; width: 566px; height: 353px;">

      Figure
      8.
      MySQL Server Basic Properties

       

    • In the Basic Properties tab, enter the server host name
      and port number. The IDE specifies localhost as the
      default server host name and 3306 as the default server
      port number.
    • Enter the administrator user name, if not displayed,
      and the
      administrator password -- the default
      administrator password is blank.
    • Click the Admin Properties tab.
    • Enter an appropriate path in the Path/URL to admin tool
      field. You
      can find the path by browsing to the location of a MySQL Administration
      application such as the MySQL Admin Tool.
    • Enter an appropriate path in the Path to start command.
      You can
      find the path by browsing to the location of the MySQL start command.
      To find the start command, look for mysqld in the bin folder of the MySQL installation directory.
    • Enter an appropriate path in the Path to stop command
      field. You
      can find the path by browsing to the location of the MySQL stop
      command. This is usually the path to mysqladmin in the bin folder of the MySQL installation directory. If the command is mysqladmin,
      in the Arguments field, type -u root stop to grant root
      permissions for stopping the server. The Admin Properties tab should
      look similar to Figure 9.

       

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/AdminProps.jpg"
      alt="MySQL Server Administration Properties"
      style="border: 0px solid ; width: 596px; height: 400px;">

      Figure
      9.
      MySQL Server Administration Properties

       

    • Click the OK button.

     

  5. Right-click on the MySQL server or Java DB database and
    select Start.
  6. Create the petcatalog database as follows:
    • Right-mouse click on the Java DB or MySQL server
      database
      and select Create Database.
      This will
      open a create Database window.
    • Enter the database name catalog for Java DB or
      petcatalog
      for MySQL.

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/createdbmysql.jpg"
      style="width: 325px; height: 137px;">



      For Java DB enter userid
      password app app as shown
      below:



      src="http://weblogs.java.net/blog/caroljmcdonald/archive/createdb.jpg"
      style="width: 341px; height: 221px;">

       Click O.K. to accept the
      displayed settings.
  7. Create the tables in the catalog database
    as follows:

    • Underneath Databases you should see a database
      connection for
      the petcatalog database. For example
      MySQL:

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/mysqlconnection.jpg"
      style="height: 22px; width: 293px;">

      or Java DB:

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/derbyconnection.jpg"
      style="width: 256px; height: 22px;">
    • Right-mouse click on the petcatalog connection and
      select Connect.
    • Right-mouse click on the petcatalog connection and
      select Execute Command. This will open up a SQL command window.
    • Copy the contents of the catalog.sql file in the catalog directory and paste the contents into
      the SQL command window, as shown in below:

       

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/CreateTables.jpg"
      alt="Creating Tables in the Database"
      style="border: 0px solid ; width: 461px; height: 318px;">

    • Click the Run SQL icon src="http://weblogs.java.net/blog/caroljmcdonald/archive/runsql.jpg"
      alt="Run SQL icon"
      style="border: 0px solid ; width: 28px; height: 28px;"> (Ctrl+Shift+E) above the SQL command window.
    • Note: It is style="color: rgb(204, 0, 0);">ok to see this: " style="color: rgb(204, 0, 0);">Error code -1, SQL state 42Y55:
      'DROP TABLE' cannot be performed on 'ITEM' because it does not exist.
      Line 2, column 1" . This just means you are deleting a table that does
      not exist.  If you need to delete and recreate the tables you will
      not  see this message the second time.
  8. View the data in the Pet
    Catalog database Item table as follows:

    • Underneath Databases you should see a database
      connection for
      the petcatalog database. For example
      MySQL:

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/mysqlconnection.jpg"
      style="height: 22px; width: 293px;">

      or Java DB:

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/derbyconnection.jpg"
      style="width: 256px; height: 22px;">
    • If the database connection is broken like in the
      following diagram:

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/brokenconnection.JPG"
      style="width: 323px; height: 161px;">

      • Right-mouse click on the petcatalog connection and
        select Connect. as shown below:

        src="http://weblogs.java.net/blog/caroljmcdonald/archive/mysqlconnect.JPG"
        style="width: 429px; height: 33px;">
      • if prompted for a password, for MySQL leave it
        blank, for JavaDB enter user app password app.
    • Expand
      the Tables node below the petcatalog database in the
      Services window. You should see the item table under the
      Tables node. You can expand the item table node to see
      the table columns, indexes, and any foreign keys, as shown in below :

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/PetcatTables.jpg"
      alt="An Expanded Table Node"
      style="border: 0px solid ; width: 400px; height: 308px;">

      Figure
      12.
      An Expanded Table Node

       

      You can view the contents of a table or column by right-clicking the
      table or column and selecting View Data as shown  below:

       

      src="http://weblogs.java.net/blog/caroljmcdonald/archive/ViewTabData.jpg"
      alt="Viewing the Contents of a Table"
      style="border: 0px solid ; width: 600px; height: 196px;">

      Figure
      13.
      Viewing the Contents of a Table




  9. Follow these
    instructions to Create a JDBC Connection pool and JDBC resource.
    Name
    the  pool mysql_petcatalog_rootPool and the jndi resource
    jdbc/petcatalog. Note: you do not have to create a JDBC connection pool
    and resource if you use the Netbeans wizard to generate JPA entities
    from database tables as described in this article GlassFish
    and MySQL, Part 2: Building a CRUD Web Application With Data
    Persistence.
  10. Open the catalog/setup/sun-resources.xml file and verify that the
    property values it specifies match those of the petcatalog database and
    jdbc resources you created. Edit the property values as necessary.

Running the Sample solution:

If you want to run the sample solution, you have to create the catalog
database tables first as described above.

 

  1. Open the catalog project as follows:
    • In NetBeans IDE, click Open Project in the File menu.
      This opens the Open Project dialog.
    • Navigate in the Open Project dialog to the catalog  directory and click the Open Project button.

     

    In response, the IDE opens the catalog project. 
    You can view the logical structure of the project in the Projects
    window (Ctrl-1).

  2. Run the catalog by right-clicking on the catalog project in the Projects window and selecting Run Project. The NetBeans
    IDE compiles the application, deploys it on Glassfish, and brings up
    the default page in your browser.  (at
    http://localhost:8080/catalog/).


For more information see the following
resources:




Comments

<p>Hi</p> <p>The download link is broken!</p> <p>It is ...

Hi
The download link is broken!
It is also the case for:
http://java.sun.com/developer/technicalArticles/glassfish/GFandMySQL_Par...
Please correct them.

But the source code of this tutorial is accessable through:
http://netbeans.org/kb/samples/pet-catalog.html

The download links are not working for me too. I have found ...

The download links are not working for me too. I have found this to be the case with others also. Thanks for the info though, it is really helpful. Sara

<p>Fixes to PetCatalog project, NetBeans ...

Fixes to PetCatalog project, NetBeans 7.0/OpenSolaris.
There were two things I had to change to make the project work:
1) Add the mysql-connector-java-5.1.16-bin.jar to the lib/ folder of my app server and restart.
2) Change l. 23 in the model.Item source code. The original line is:
@Table(name="Item")
On systems like mine where MySQL tables are case-sensitive, this is a problem. The table is installed as "petcatalog item" not "petcatalog.Item". I changed this line to:
@Table(name = "item")
Build/redeploy and the application works like a champ.

@mfernest I also had the problem with case-sesitive ...

@mfernest I also had the problem with case-sesitive mysql-server ( ubuntu ) you can alternatively change the default behavior of mysql on *nix systems to be case-insensitive by switching the global mysql variable

lower_case_table_names. On my system I needed to change /etc/mysql/my.cnf as follows:<br />
[mysqld]<br />
#<br />
# * Basic Settings<br />
#<br />
lower_case_table_names=1
Another thing that I needed to configure was the mysql-server access rights, because I have installed it on Virtual Machine (so a remote machine). Now it works, and it is a great "hello world" project to start with. Small and simple.

Hello, I am a student in my

Hello,
I am a student in my 2nd year. I have taken Java 1 and 2. Near the end of my second class, I began using Netbeans because of its lean towards graphic oriented programming. I have been pursuing tutorials to expand my knowledge and that was how I discovered this link.
I have signed up with java.net and am fascinated by the bulk of material available. I have downloaded the plug in for glass fish and am running the latest version of NetBeans. I want to try this project but I am not able to download the sample content. It says I do not have access to the project.
I am open to any suggestions that you have (anyone) and I hope to hear from you soon.
Thanks,
Paul

Java EE 6 Pet Catalog with

Excellent tutorial, if I wanted to do a search button, how would you do?.
I tried to modify the Catalog.java, but without any results

petcatalog don´t work at all

I did the practice two times becouse of HTTP Status 500 - -------------------------------------------------------------------------------- type Exception report message descriptionThe server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException root cause javax.ejb.EJBException root cause Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLSyntaxErrorException: La tabla/vista 'ITEM' no existe. Error Code: -1 Call: SELECT COUNT(ITEMID) FROM ITEM Query: ReportQuery(referenceClass=Item sql="SELECT COUNT(ITEMID) FROM ITEM") root cause java.sql.SQLSyntaxErrorException: La tabla/vista 'ITEM' no existe. root cause org.apache.derby.client.am.SqlException: La tabla/vista 'ITEM' no existe. note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.0.1 logs. -------------------------------------------------------------------------------- GlassFish Server Open Source Edition 3.0.1 The conclusion: the catalog.sql does not creat the correct tables that you mention in this tutorial, I had tryed both with msql and Jdbc I hope some body can help me !!! I am studying NETBEANS 6.9 IDE for 3 weeks and yet can run any decent proyect that manage a CRUD db. Thanks for your help.

org.apache.derby.client.am.SqlException

The application connects initially to the Derby database and don't find right tables there. In "persistence.xml" modify the value of jta-data-source as follows: jdbc/petcatalog The app works then correctly.

error

hi i got the following error, but cannot find the issue as the item table should be created. any ideas ??? HTTP Status 500 - type Exception report message descriptionThe server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException root cause javax.ejb.EJBException root cause Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'ITEM' does not exist. Error Code: -1 Call: SELECT COUNT(ITEMID) FROM ITEM Query: ReportQuery(referenceClass=Item sql="SELECT COUNT(ITEMID) FROM ITEM") root cause java.sql.SQLSyntaxErrorException: Table/View 'ITEM' does not exist. root cause org.apache.derby.client.am.SqlException: Table/View 'ITEM' does not exist. note The full stack traces of the exception and its root causes are available in the GlassFish v3 logs. GlassFish v3

The most easiest fix is to change the name of the table from ...

The most easiest fix is to change the name of the table from item to ITEM in catalog.sql. This appears to work for me.

Good clean simple example

Deleted (sorted problem out)

NetBeans-ready sample project

I assume this is the same tutorial as we can get as a netbeans sample project from kenai.com ? I got it right in NetBeans, via Team > Kenai > Open Kenai Project, and then I searched for "samples catalog", and within that, I got the folder "NB68".

NetBeans-ready sample project

yes, this is the same example, except for Netbeans I cleaned up the images to save space

Excellent explanation

Beautiful girl and very nice explanation.

Excellent explanation

True, although I'm not exactly what relevance the "beautiful girl" comment has to the actual content of this link. But yes, good information -- and a cool use for Java!

what a girl with a dog catalog, cute

i had deploy this project as it is,you deploy but i can`t get success, my machine diplay a error on browse HTTP cant find folder