Generating a JavaServer Faces 2.0 CRUD Application from a Database
In this tutorial, you use the NetBeans IDE to create a web application that interacts
with a back-end database. The application provides you with the ability to view and
modify data contained in the database - otherwise referred to as CRUD (Create,
Read, Update, Delete) functionality. The application you develop relies on:
JavaServer Faces (JSF) 2.0 for front-end web pages, validation handling,
and management of the request-response cycle.
Java Persistence API (JPA) 2.0 using EclipseLink to generate entity
classes from the database, and manage transactions. (EclipseLink is the reference
implementation for JPA, and is the default persistence provider for the GlassFish
application server.)
Enterprise JavaBeans (EJB) 3.1, which provides you with stateless EJBs
that access the entity classes, and contain the business logic for the application.
The IDE provides two wizards which generate all of the code for the application. The first
is the Entity Classes from Database wizard which enables you
to generate entity classes from the provided database. After you create entity classes, you
use the JSF Pages from Entity Classes wizard to create
JSF managed beans and EJBs for the entity classes, as well as a set of Facelets pages
to handle the views for entity class data. The final section of the tutorial,
Exploring the Application, is optional, and provides numerous
exercises to help you to better understand the application and become more familiar with
the IDE.
Note: This tutorial is only applicable to NetBeans IDE 6.8.
NetBeans 6.5/6.7 users: See the 6.7 version of this tutorial.
NetBeans 6.1 users: See the 6.1 version of this tutorial.
This tutorial uses a consulting agency database called consult. The database
is not included when you install the IDE so you need to first create the database to follow
this tutorial.
The consult database was designed to demonstrate the scope of IDE support for handling a
variety of database structures. The database is thus not intended as an example of
recommended database design or best-practice. Instead, it attempts to incorporate many
of the relevant features that are potentially found in a database design. For example,
the consult database contains all possible relationship types, composite primary keys,
and many different data types. See the tables below for a more detailed overview of the
database structure.
Perform the following steps to create a database and connect to it from the IDE.
Download mysql-consult.zip
and extract the archive to your local system. When you extract the archive you will
see the SQL scripts for creating and populating the database. The archive also has
scripts for dropping tables.
In the Services window, expand the Databases node, right-click the MySQL node and
choose Start Server.
Right-click the MySQL Server node and choose Create Database.
Type consult as the Database Name in the Create MySQL Database
dialog. Click OK. A new node appears under the Databases node
(jdbc:mysql://localhost:3306/consult [root on Default schema]).
Right-click the new node and choose Connect.
Choose File > Open File from the main menu and navigate to the extracted file
mysql_create_consult_v2.sql. Click Open. The file automatically
opens in the the SQL editor.
Make sure that the consult database is selected in the Connection drop-down list
in the SQL editor toolbar, then click the Run SQL (
) button.
When you click Run SQL, the following output appears in the Output window.
Examining the Database Structure
To see the if the tables were created correctly, expand the Tables node under the
database connection node. You can expand a table node to see the table columns,
indexes and any foreign keys. You can right-click a column and choose Properties
to view additional information about the column.
Note: If you do not see any tables under the Tables
node, right-click the Tables node and choose Refresh.
Looking at the structure of the consult database, you can see that the
database contains tables that have a variety of relationships and various field
types. When creating entity classes from a database, the IDE automatically generates
the appropriate code for the various field types.
The following table describes the tables found in the consult database.
Database Table
Description
Design Features
CLIENT
A client of the consulting agency
Non-generated, composite primary key (whose fields
do not constitute a foreign key)
CONSULTANT
An employee of the consulting agency whom clients
can hire on a contract basis
Includes a resume field of type LONG VARCHAR
CONSULTANT_STATUS
A consultant's status with the consulting agency
(for example, Active and Inactive are possible statuses)
Non-generated primary key of type CHAR
RECRUITER
An employee of the consulting agency responsible
for connecting clients and consultants
PROJECT
A project that a client staffs with consultants of
the consulting agency
Non-generated, composite primary key that includes
two fields constituting a foreign key to the CLIENT table
BILLABLE
A set of hours worked by a consultant on a project,
for which the consulting agency bills the relevant client
Includes an artifact field of type CLOB
ADDRESS
A client's billing address
PROJECT_CONSULTANT
Join table indicating which consultants are currently
assigned to which projects
Cross-references PROJECT and CONSULTANT, the former
having a composite primary key
The consult database includes a variety of relationships. When creating
entity classes from a database, the IDE automatically generates the properties of the
appropriate Java type based on the SQL type of the columns. The following table
describes the entity relationships for the consult database. (Inverse
relationships are not shown.)
Entity
Related Entity
Relationship Information
Description
CLIENT
RECRUITER
nullable one-to-one with manual editing; nullable one-to-many
if not edited
CLIENT has many RECRUITERs and RECRUITER has zero or one CLIENT
(if not manually edited)
CLIENT
ADDRESS
non-nullable one-to-one
CLIENT has one ADDRESS and ADDRESS has zero or one CLIENT
CLIENT
PROJECT
non-nullable one-to-many; in a Project entity, the value of the
client field is part of the Project's primary key
CLIENT has many PROJECTs and PROJECT has one CLIENT
CONSULTANT
PROJECT
many-to-many
CONSULTANT has many PROJECTs and PROJECT has many CONSULTANTs
CONSULTANT
BILLABLE
non-nullable one-to-many
CONSULTANT has many BILLABLEs and BILLABLE has one CONSULTANT
CONSULTANT_STATUS
CONSULTANT
non-nullable one-to-many
CONSULTANT_STATUS has many CONSULTANTs and CONSULTANT has one
CONSULTANT_STATUS
CONSULTANT
RECRUITER
nullable one-to-many
CONSULTANT has zero or one RECRUITER and RECRUITER has many
CONSULTANTs
BILLABLE
PROJECT
non-nullable one-to-many
BILLABLE has one PROJECT and PROJECT has many BILLABLEs
Now that the database is created, you can create the web application and use the
Entity Classes from Database wizard to generate entity classes based on the database
tables.
Creating the Web Application Project
In this exercise you create a web project and add the JavaServer Faces framework to the
project. When you create the project, you will select JavaServer Faces in the Frameworks
panel of the New Project wizard.
Choose File > New Project (Ctrl-Shift-N).
Select Web Application from the Java Web category. Click Next.
Type ConsultingAgency for the project name and set the project
location. Click Next.
Set the server to GlassFish v3 and set the Java EE Version to Java EE 6 Web. Click Next.
In the Frameworks panel, select the JavaServer Faces option. Click Finish.
When you click Finish, the IDE generates the web application project and opens
index.xhtml in the editor.
Generating the Entity Classes from the Database
After connecting to a database in the IDE, you can use the Entity Classes from Database
wizard to quickly generate entity classes based on the tables in the database. The IDE
can generate entity classes for each table that you select, and can also generate any
necessary entity classes for related tables.
In the Projects window, right-click the ConsultingAgency project node,
and choose New > Entity Classes from Database. (If this option is not listed,
choose Other. Then, in the File wizard, select the Persistence category, then Entity
Classes from Database.)
Select New Data Source from the Data Source drop-down list to open the Create Data Source dialog.
Type jdbc/consult as the JNDI Name and select jdbc:mysql://localhost:3306/consult [root on Default schema]
as the Database Connection.
Important: Your database needs to be password-protected
to create a data source and work with Eclipselink in this tutorial. If you
are using the default MySQL root account with an empty password,
you can set the password from a command-line prompt.
For example, to set your password to nbuser, in the command-line
prompt navigate to your MySQL installation's bin directory and enter the
following:
shell> mysql -u root
mysql> UPDATE mysql.user SET Password = PASSWORD('nbuser')
-> WHERE User = 'root';
mysql> FLUSH PRIVILEGES;
Click OK to close the dialog box and return to the wizard. The tables in the consult
database appear in the Available Tables listbox.
Click the Add All button to select all tables contained in the database. Click Next.
Type jpa.entities as the Package name. Make sure that the checkbox to
generate named queries is selected.
Click the Create Persistence Unit button to open the Create Persistence Unit dialog box.
Click Create in the dialog box to create the persistence unit and return to the wizard.
Note: You can keep the default values for the persistence
unit.
Click Finish. The IDE generates the entity classes in the jpa.entities
package of the project.
When using the wizard to create entity classes from a database, the IDE examines the
relationships between database tables. In the Projects window, if you expand the
jpa.entities package node, you can see that the IDE generated an entity
class for each table except for the PROJECT_CONSULTANT table. The IDE
did not create an entity class for PROJECT_CONSULTANT because the table
is a join table.
The IDE also generated two additional classes for the tables with composite primary keys:
CLIENT and PROJECT. The primary key classes for these tables
(ClientPK.java and ProjectPK.java) have PK appended
to the name.
If you look at the generated code for the entity classes you can see that the wizard added
@GeneratedValue annotations to the auto-generated ID fields and @Basic(optional = "false") annotations to some of the fields in the entity classes.
Based on the @Basic(optional = "false") annotations, the JSF Pages from Entity Classes wizard can generate code that
includes checks to prevent non-nullable column violations for those fields.
Generating JSF Pages From Entity Classes
Now that the entity classes are created, you can create the web interface for
displaying and modifying the data. You will use the JSF Pages from Entity Classes
wizard to generate JavaServer Faces pages. The code generated by the wizard is
based on persistence annotations contained in the entity classes.
For each entity class, the wizard generates the following:
a stateless session bean for creation, retrieval, modification and
removal of entity instances
a JSF session-scoped, managed bean
a directory containing four Facelets files for CRUD capabilities (Create.xhtml,
Edit.xhtml, List.xhtml, and View.xhtml)
utility classes used by the JSF managed beans (JsfUtil,
PaginationHelper)
a properties bundle for localized messages, and a corresponding entry in the
project's Faces configuration file (A faces-config.xml file is
created if one does not already exist.)
auxilary web files, including a default stylesheet for rendered components,
and a Facelets template file
To generate the JSF pages:
In the Projects window, right-click the project node and choose New > JSF Pages
from Entity Classes to open the wizard. (If this option is not listed, choose Other.
Then, in the File wizard, select the JavaServer Faces category, then JSF Pages
from Entity Classes.)
The Available Entity Classes box lists the seven entity classes contained in the
project. The box does not list the embeddable classes (ClientPK.java
and ProjectPK.java).
Click Add All to move all the classes to the Selected Entity Classes box.
Click Next.
In Step 3 of the wizard, Generate JSF Pages and Classes, type jpa.session
for the JPA Session Bean Package.
Type jsf for the JSF Classes Package.
Enter '/resources/Bundle' into the Localization Bundle Name field. This will
generate a package named resources which the Bundle.properties
file will reside in. (If you leave this blank, the properties bundle will be created
in the project's default package.)
To let the IDE better accommodate your project conventions, you can
customize any files generated by the wizard. Click the Customize Template link to
modify the file templates used by the wizard.
In general, you can access and make changes to all templates maintained by the IDE
using the Template Manager (Tools > Templates).
Click Finish. The IDE generates the stateless session beans in the jpa.session
package, and the JSF session-scoped, managed beans in the jsf package. Each
stateless session bean handles the operations for the corresponding entity class, including
creating, editing, and destroying instances of the entity class via the Java Persistence API.
Each JSF managed bean implements the javax.faces.convert.Converter interface and
performs the work of converting instances of the corresponding entity class to String
objects and vice versa.
If you expand the Web Pages node, you can see that the IDE generated a folder for each of the
entity classes. Each folder contains the files Create.xhtml, Edit.xhtml,
List.xhtml and View.xhtml. The IDE also modified the index.xhtml
file by inserting links to each of the List.xhtml pages.
Each JSF managed bean is specific to the four corresponding Facelets files and includes code
that invokes methods in the appropriate session bean.
Expand the resources folder node to locate the default jsfcrud.css
stylesheet that was generated by the wizard. If you open the application welcome page
(index.xhtml) or the Facelets template file (template.xhtml)
in the editor, you will see that it contains a reference to the stylesheet.
<h:outputStylesheet name="css/jsfcrud.css"/>
The Facelets template file is used by each of the four Facelets files for each entity class.
If you expand the Source Packages node you can see the session beans, JSF managed beans,
utility classes, and properties bundle that the wizard generated.
The wizard also generated a Faces Configuration file (faces-config.xml) in
order to register the location of the properties bundle. If you expand the Configuration
Files node and open faces-config.xml in the XML editor, you can see that
the following entry is included.
Also, if you expand the new resources package, you'll find the Bundle.properties
file that contains messages for the client's default language. The messages have been
derived from the entity class properties.
To add a new property bundle, right-click the Bundle.properties file
and choose Customize. The Customizer dialog enables you to add new locales to your application.
Exploring the Application
Now that your project contains entity classes, EJB session beans to control the
entity classes, and a JSF-powered front-end to display and modify database, try
running the project to see the results.
The following is a series of short, optional exercises that help you to become familiar
with the application, as well as the features and functionality offered to you by
the IDE.
To run the project, either right-click the project node in the Projects window
and choose Run, or click the Run Project (
) button in the main toolbar.
When the application's welcome page displays, you are provided with a list of
links enabling you to view entries contained in each database table.
The links were added to the welcome page (index.xhtml) when you
completed the JSF Pages from Entity Classes wizard. They are provided as
entry points into the Facelets pages that provide CRUD functionality on the
Consulting Agency database.
<h:body>
Hello from Facelets
<h:form>
<h:commandLink action="/address/List" value="Show All Address Items"/>
</h:form>
<h:form>
<h:commandLink action="/billable/List" value="Show All Billable Items"/>
</h:form>
<h:form>
<h:commandLink action="/client/List" value="Show All Client Items"/>
</h:form>
<h:form>
<h:commandLink action="/consultant/List" value="Show All Consultant Items"/>
</h:form>
<h:form>
<h:commandLink action="/consultantStatus/List" value="Show All ConsultantStatus Items"/>
</h:form>
<h:form>
<h:commandLink action="/project/List" value="Show All Project Items"/>
</h:form>
<h:form>
<h:commandLink action="/recruiter/List" value="Show All Recruiter Items"/>
</h:form>
</h:body>
Click the 'Show All Consultant Items' link. Looking at the code above, you
can see that the target page is /consultant/List.xhtml. (In JSF 2.0, the file
extension is inferred due to implicit navigation.)
The database currently doesn't contain any sample data. You can add data manually
by clicking the 'Create New Consultant' link and using the provided
web form. This triggers the /consultant/Create.xhtml page to display.
You can also run an SQL script in the IDE to populate tables with sample data. The
following sub-sections explore both options.
You can click the index link to return to the links listed in the welcome page.
The links provide you with a view of the data held in each database table and
trigger the List.xhtml file for each entity folder to display. As
is later demonstrated, after you add data to the tables, other links will display
for each entry enabling you to view (View.xhtml), edit (Edit.xhmtl),
and destroy data for a single table record.
Populating the Database with an SQL Script
Run the provided script, which generates sample data for the database tables. The script
(mysql_insert_data_consult_v2.sql) is included in the Consulting Agency Database
zip file which you can download from the required software
table.
Choose File > Open File from the main menu, then navigate to the location of the
script on your computer. Click Open. The file automatically opens in the IDE's SQL
editor.
Make sure that the consult database is selected in the Connection
drop-down list in the SQL editor toolbar.
Either right-click in the editor and choose Run Statement, or click the Run SQL (
) button. You can see the result of the script execution in the Output window.
Restart GlassFish. This is a necessary step to enable the server to reload and cache
the new data contained in the consult database. To do so, click the GlassFish
tab in the Output window (The GlassFish tab displays the server log.), then click the
Restart Server ( ) button in the left margin. The GlassFish server stops,
then restarts.
Run the project again and click the 'Show All Consultant Items' link. You'll
see that the list is no longer empty.
NetBeans Database Support
You can use the IDE's database table viewer to display and modify table
data maintained directly in the database. For example, right-click the
consultant table in the Services window, and choose View
Data.
The SQL query used to perform the action displays in the upper portion
of the editor, and a graphial view of the table displays beneath.
Double-click inside table cells to perform inline modifications to data.
Click the Commit Records ( )
icon to commit changes to the database.
Open the /consultant/List.xhtml page in the editor. Line 8 indicates that
the page relies on the Facelets template.xhtml file to render.
<ui:composition template="/template.xhtml">
To display line numbers, right-click in the editor's left margin and
choose Show Line Numbers.
Use the IDE's Go to File dialog to open template.xhtml. Press Alt-Shift-O
(Ctrl-Shift-O on Mac), then begin typing template.
Click OK (or press Enter).
The template applies the <ui:insert> tags to insert content from
other files into its title and body. Place your cursor on the <ui:insert>
tag, then press Ctrl-Space to invoke a documentation popup window.
You can press Ctrl-Space on JSF tags and their attributes to invoke a documentation
pop-up. The documentation you see is taken from the descriptions provided in the
official JSF
Tag Library Documentation.
Switch back to the List.xhtml file (press Ctrl-Tab). The
<ui:define> tags are used to define the content that will
be applied to the template's title and body. This pattern is used for all four
Facelets files (Create.xhtml, Edit.xhtml, List.xhtml,
and View.xhtml) generated for each entity class.
Place your cursor on any of the EL expressions used for localized messages contained
in the Bundle.properties file. Press Ctrl-Space to view the localized
message.
In the above image, you can see that the EL expression resolves to 'List',
which is applied to the template title and can be verified from the page rendered in the
browser.
Scroll to the bottom of the file and locate the code for the Create New Consultant
link (Line 92). This is as follows:
Press Ctrl-Space on the commandLink's action attribute to
invoke the documentation pop-up.
The action attribute indicates the method that handles the request when
the link is clicked in the browser. The following documentation is provided:
MethodExpression representing the application action to invoke when this
component is activated by the user. The expression must evaluate to a public
method that takes no parameters, and returns an Object (the toString() of
which is called to derive the logical outcome) which is passed to the
NavigationHandler for this application.
In other words, the action value typically refers to a method in a
JSF managed bean that evaluates to a String. The string is then used
by JSF's NavigationHandler to forward the request to the appropriate
view. You verify this in the following steps.
Place your cursor on consultantController and press Ctrl-Space. The
editor's code completion indicates that consultantController is a
JSF managed bean.
Move your cursor to prepareCreate and press Ctrl-Space. Code completion
lists methods contained in the ConsultantController managed bean.
Press Ctrl (⌘ on Mac), then hover your mouse over prepareCreate. A
link is formed, enabling you to navigate directly to the prepareCreate()
method in the ConsultantController managed bean.
Click the link and view the prepareCreate() method (displayed below).
public String prepareCreate() {
current = new Consultant();
selectedItemIndex = -1;
return "Create";
}
The method returns Create. The NavigationHandler
gathers information behind the scenes, and applies the Create
string to the path which targets the view sent in response to the request:
/consultant/Create.xhtml. (In JSF 2.0, the file
extension is inferred due to implicit navigation.)
Exploring Database Integrity with Field Validation
From the Consultants List page in the browser,
click the 'Create New Consultant' link. As demonstrated in the
previous sub-section, this triggers the /consultant/Create.xhtml
page to render.
Enter the following details into the form. For the time being, leave both RecruiterId
and StatusId fields blank.
Field
Value
ConsultantId
2
Email
Password
jack.smart
HourlyRate
75
BillableHourlyRate
110
HireDate
07/22/2008
Resume
I'm a great consultant. Hire me - You won't be disappointed!
RecruiterId
---
StatusId
---
Click Save. When you do so, a validation error is flagged for the StatusId field.
Why did this happen? Reexamine the entity-relationship diagram for the
Consulting Agency database. As stated in the relationships table
above, the CONSULTANT and CONSULTANT_STATUS tables share a non-nullable,
one-to-many relationship. Therefore, every entry in the CONSULTANT table must contain
a reference to an entry in the CONSULTANT_STATUS table. This is denoted by the
consultant_fk_consultant_status foreign key that links the two tables.
You can view foreign keys held by tables by expanding a table's Foreign Keys
node in the Services window (Ctrl-5; ⌘-5 on Mac).
To overcome the validation error, select entity.ConsultantStatus[statusId=A] from
the StatusId drop-down list.
Note: You can leave the RecruiterId field blank.
As indicated in the database entity-relationship diagram, there is
a nullable, one-to-many relationship between the CONSULTANT and RECRUITER
tables, meaning that entries in CONSULTANT do not need to be associated with
a RECRUITER entry.
Click Save. A message displays, indicating that the consultant entry was successfully saved.
If you click Show All Consultant Items, you'll see the new entry listed in the
table.
In general, the generated Facelets pages provide errors for user input that introduces:
empty fields for non-nullable table cells.
modifications to data that cannot be altered (e.g., primary keys).
insertion of data that is not of the correct type.
modifications to data when a user's view is no longer synchronized with
the database.
Editing Entity Classes
In the previous sub-section, you saw how the StatusId drop-down list provided
you with the not-so-user-friendly entity.ConsultantStatus[statusId=A] option.
You may already be aware that the text displayed for each item in this drop-down is a string
representation for each ConsultantStatus entity encountered (i.e., The entity
class' toString() method is called).
This sub-section demonstrates how you can use the editor's code completion, documentation,
and navigation support to make this conclusion. It also has you prepare a more user-friendly
message for the drop-down list.
Open the /consultant/Create.xhtml file in the editor. This is the Create
New Consultant form which you just viewed in the browser. Scroll down to the code for
the StatusId drop-down (shown in bold below).
Examine the value applied to the <f:selectItems> tag.
The value attribute determines the text that displays for each item in
the drop-down list.
Press Ctrl-Space on itemsAvailableSelectOne. The editor's
code completion indicates that the ConsultantStatusController's
getItemsAvailableSelectOne() method returns an array of
SelectItem objects.
Press Ctrl (⌘ on Mac), then hover your mouse over itemsAvailableSelectOne.
A link is formed, enabling you to navigate directly to the getItemsAvailableSelectOne()
method in the ConsultantStatus entity's source code. Click this link.
Place your cursor on the SelectItem[] return value in the method
signature, and press Ctrl-Space to invoke the documentation pop-up.
Click the web browser (
) icon in the documentation window to open the Javadoc
in an external web browser.
As you can see, the SelectItem class belongs to the JSF framework.
The UISelectOne component, as mentioned in the documentation, is represented
by the <h:selectOneMenu> tag from the markup which you examined in
Step 1 above.
Press Ctrl (⌘ on Mac), then hover your mouse over findAll(). A pop-up
appears, displaying the method signature.
You can see that here ejbFacade.findAll() returns a List of
ConsultantStatus objects.
Navigate to JsfUtil.getSelectItems. Hover your mouse over
getSelectItems and press Ctrl (⌘ on Mac), then click
the link that displays.
The method loops through the list of entities (i.e, the List
of ConsultantStatus objects), creating a SelectItem
for each. As indicated in bold below, each SelectItem
is created using the entity object and a label for the object.
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
The label is created using the entity's toString() method, and
is the representation of the object when rendered in the response. (See the
Javadoc definition for the SelectItem(java.lang.Object value, java.lang.String label)
constructor.)
Now that you have verified that the entity toString() method
is what is rendered in the browser when you view items in a drop-down list,
modify the ConsultantStatustoString() method.
Open the ConsultantStatus entity class in the editor. Modify the
toString method to return the statusId and
description. These are entity properties which correspond to
the two columns of the CONSULTANT_STATUS table.
Run the project again. When the browser displays the welcome page, click the
Show All Consultant Items link, then click Create New Consultant.
Inspect the StatusId drop-down. You'll see that it now displays
the status ID and description for the one record contained in the database's
CONSULTANT_STATUS table.