Integrating Ajax and EJB 3.0/JPA - Building a Web application using ICEFaces, JPA and Oracle JDeveloper

By Juan Camilo Ruiz & Shay Shmeltzer
March 2007

Introduction

In this tutorial, We'll build a Web page that uses the new Java Persistence API (JPA) combined with JSF and the open sourced ICEFaces rich UI components. JPA provides a simple data model and ICEFaces provides Ajax based components for Web user interfaces.

Topics

This tutorial covers the following topics:

Overview

Prerequisites

Installing ICEFaces on JDeveloper

Creating a Database Connection

Building the Data Model with JPA

Creating a Backing Bean for the UI

Creating a JSF Page to display an ICEFaces Datatable

Running the Application

Adding Table Pagination

Summary

 

Overview

You will create a basic ICEFaces data table for viewing departments' information. The underlying details of the model will be built with EJB 3.0 and JPA. You will then add pagination to the data table to create a more appealing presentation. Finally, you will test run the application with JDeveloper's embedded server.

You can download a copy of the completed JDeveloper project from here for reference.
Note - Oracle JDeveloper comes pre-packaged with the Oracle ADF Faces set of JSF components. These components also offer a lot of AJAX type functionality. You might be interested to learn more about them here.

Back to Topic List

Prerequisites

Before starting the tutorial, you should:

1.

Have access to or have installed Oracle JDeveloper 10g Release 3 (10.1.3.2) Production. Oracle JDeveloper is a free Java IDE with exceptional support for building enterprise Java applications. You can download it from the Oracle Technology Network.

2.

Have access to or have installed the Oracle HR Sample Schemas.
This schema comes built in with default installations of both the Oracle database and the free Oracle XE databases - make sure the HR user in the database is unlocked. Instructions for installing the HR schema and creating a connection to it in JDeveloper are available here.

3.

Start JDeveloper. Double-click the JDeveloper executable ( jdeveloper.exe ) found in the root directory where you unzipped it.

If the Migrate User Settings dialog box opens, click No.

Back to Topic List

Installing ICEFaces on JDeveloper

1.

Download ICEfaces-v1.5.3-JDeveloper.zip from here

 

2.

In JDeveloper, go to Help | Check for Updates from JDeveloper main menu, choose Install from Local file and browse for the ICEfaces-v.1.5.3-jDeveloper.zip

Click Next to continue

3.

JDeveloper needs to restart. After this is done, verfify that the ICEFaces libraries were installed by going to Tools | Manage Libraries



In the same place also verify that the JSP Tag Libraries were installed

Back to Topic List

Creating a Database Connection

If you haven't already created a JDBC connection to the HR schema, then perform the following steps:

1.

Click the Connections tab. If the Connections tab is not showing, choose View | Connection Navigator from the JDeveloper main menu.

 

2.

Right-click the Database node and choose New Database Connection from the context menu.

 

3.

When the Welcome page of the Create Database Connection wizard opens, click Next.

On the Type page of the wizard, enter hrconn as the Connection Name. Click Next to continue.

 

4.

On the Authentication page of the wizard, enter hr in the Username field and hr in the Password field. Check the Deploy password  box.

Click Next to continue.

 

5.

On the Connection page of the wizard, the default values for the connection should be the following:

Driver: thin

Host Name: localhost

JDBC Port: 1521

SID: ORCL (For Oracle XE database the value of the SID is XE)

Leave the fields set to these default values if you have the database installed locally. If you are using a remote database, enter the appropriate values for the connection to the database. If you do not know these values, check with your database administrator.

Click Next to continue.

 

6.

Click Test Connection.

If the database is available and the connection details are correct, you  should see the word Success! displayed in the Status window.

If an error occurs, verify the connection settings, click Back to make any necessary changes, and then retest the connection.

If the connection is successful, click Finish to complete the connection.

You have just created a connection to the database that supplies data for the application you will build in this tutorial. Note that the database navigator allows you to browse and even edit objects in your database connection.

Back to Topic List

Building the Data Model with JPA

The business model provides data access and validation for an application. The model, regardless of the client implementation, always validates the data. This cleanly separates the validation and business rules from the user interface.

To create an application in JDeveloper and a JPA model for the application, you will perform the following tasks:

Create New Application and Projects

Create Business Logic using JPA and EJB

Back to Topic List

Create a New Application and Projects

In JDeveloper, you always work with projects contained in an application.

The application is the highest level in the JDeveloper control structure. It is a view of all related objects you need while working. An application keeps track of your projects while you are developing Java programs.

A JDeveloper project is an organizational structure used to logically group related files. You can add multiple projects to an application in order to organize, access, modify, and reuse your source code. In the Applications Navigator, projects are displayed in the second level in the hierarchy, as sub nodes of the application.

Before you create any application components, you must first create the application and an initial project. To do this, perform the following steps:

1.

Click the Applications Navigator tab to go back to the Applications Navigator.

Right-click the Applications node and select New Application from the context menu.

 

2.

In the Create Application dialog box, enter the Application Name iceFacesDemo . Notice that as you enter the application name, the directory name changes automatically.

Enter oracle.com as the Application Package Prefix.

Select the Web Application [JSF, EJB, Toplink ] value from the Application Template drop-down list.

Click OK.

 

3.

Having created the Application together with the Model (JPA) and ViewController (user interface) projects. Add ICEFaces integration to the ViewController project. Right-click the ViewController node and select ICEFaces Integration

Review the actions, click  YES

4.

After this is done check the ICEFaces libraries have been added in the Project Properties

 

5.

Click OK.

Click Save All  on the toolbar to save your work. Alternatively, you can select File | Save All from the menu.

Back to Topic

Back to Topic List

Creating Business Logic using JPA and EJB

In this section you will create an entity bean based on Java Persistence Architecture (JPA) from a relational database table called Departments. In the entity bean you can implement methods and named queries that interact with your data source.

After creating the entity bean you are going to create an EJB session bean that will act as a session facade and will encapsulate business logic and business data, exposing any necessary interfaces.

To create the data model of your application perform the following steps:

1.

In the Applications Navigator, right-click the Model project and from the context menu, select New.

 

2.

In the New Gallery, expand Business Tier in the Categories list and select the EJB node. In the Items list, select Entity From Tables (JPA/EJB3.0) and click OK.

 

3.

If the Welcome page of the Create Entity from Tables wizard displays, click Next.


On the Database Connection Details, choose hrconn that was created before



Click Next.

4.

On Select Tables, click on Query to bring all the tables from the database connection. Select the table Departments from the Available list of tables to Selected list.




Click Next.

5.

Choose java.util.List as the Collection Type for Relationship Fields.




Click Next.
Click Finish.

6.

Review the Departments.java bean that was created with the code that was generated




We have created a basic EJB 3.0 entity bean based on the Table. Now we are going to create a session facade bean to encapsulate business logic and expose methods and interfaces to the outside world.

7.

In the Applications Navigator, right-click the Model project and from the context menu, select New.

8.

In the New Gallery, expand Business Tier in the Categories list and select the EJB node. In the Items list, select Session Bean (EJB 1.1/2.x/3.0) and click OK.

9.

If the Welcome page of the Create Session wizard displays, click Next.

On the EJB Name and Options page of the wizard, set the values to those shown below.

Field

Value

EJB Name

DepPublicFacade

Session Type

Stateless

Transaction Type

Container

Generate Session Façade Methods

Check box selected (so that methods to query and persist data are generated)

Entity Implementation

EJB 3.0 Entities

Stateless session beans do not have an internal state. They do not keep track of the information that is passed from one method call to another. Each invocation of a stateless business method is independent of its previous invocation. You only need a stateful session bean for applications such as online shopping carts that need to maintain a conversational state across method invocations.

By specifying a Transaction Type of Container, you are enabling the container to manage transactions so that you do not have to code transaction mechanisms. You would change this only if you wanted to write your own transaction mechanisms.

Click Next.

 

10.

On the Session Façade page of the wizard, ensure that all the check boxes are selected, because you want to have the session facade incorporate all the methods and named queries. Click Next.

model11.jpg

 

11.

On the Class Definitions page of the wizard, ensure that Bean Class is set to oracle.com.model.DepPublicFacadeBean . The default directory is acceptable. Click Next.

model12.jpg

 

12.

On the EJB Component Interfaces page of the wizard:

Click Next.

model13.jpg

Click Finish to complete the process.

 

13.

Review the code that was generated

model14.jpg

Click Save All  on the JDeveloper toolbar, or select File | Save All from the menu.

Back to Topic

Back to Topic List

Creating a Backing Bean for the UI

When you created the application, you created it with two projects: Data Model and User Interface. The Data Model project contains the JPA persistence that serves as the business model for your application. The User Interface project is for the view portion of your application, which defines the user interface components.

We are going to use JSF to develop our user interface layer. First, we are going to create a backing bean which is going to provide the bridge to access the model layer from the UI layer. Our backing bean provides a simple java class that can be used by more than one JSF page to call methods from the model layer or keep data variables to be used by more than one page.

We'll verify the structure of our project and then create a backing bean. Perform the following steps:

1.

Right-click on the ViewController project and select Project Properties

Go to Dependencies  and check Model.jpr to ensure we can call methods from the Model in the views.

view01a.jpg

In the J2EE Application change the application name and the context root for iceFacesDemo

view01b.jpg

Click Save All  to save your work.

2.

In the Applications Navigator, right-click the ViewController project and select Open JSF Navigation from the context menu.

 

3.

JDeveloper provide us with three ways of  editing the faces-config.xml configuration file, which is the core of the JSF controller layer. In the design editing mode - you can visually design page flows for your application. The source tab at the bottom will allow you to directly edit the XML code. We are going to use the overview tab for declarative editing of the file.

Select Overview tab from the  lower left side

view02.jpg 

Select Managed Beans from the left area, then on the right select New

4.

Assign the values

Field

Value

Name

DepartmentBean

Class

oracle.com.view.DepartmentsBean

Scope

session

Generate Class if It Does Not Exist

Check box selected (so the class gets generated)


view03.jpg

Click OK

Click Save All  on the JDeveloper toolbar, or select File | Save All from the menu.

5.

Open the DepartmentsBean.java, on the ViewController project and expand Application Sources-> oracle.com.view double-click on DepartmentsBean.java

view04.jpg

6.

Replace the code of the class with the following code that creates a method that returns a list of departments from your entity bean.
Note - the code to access the EJB is similar to the code you can generate by right clicking the session facade and creating a "sample EJB client" in JDeveloper.

package oracle.com.view;

import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import oracle.com.model.DepPublicFacade;

public class DepartmentsBean {

    private DepPublicFacade model;

    public DepartmentsBean() {
        try {
            final Context context = getInitialContext();
            model = (DepPublicFacade)context.lookup("DepPublicFacade");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public List getDepartments() {
        return model.queryDepartmentsFindAll();
    }
    private static Context getInitialContext() throws NamingException {
        // Get InitialContext for Embedded OC4J
        // The embedded server must be running for lookups to succeed.
        return new InitialContext();
    }
}

Import the necessary packages clicking CTRL+ ENT  on the different objects you are using.

After you have no warnings of errors. Click Save All  to save your work.

Back to Topic List

Creating a JSF Page to display an ICEFaces DataTable

You will now create the user interface. You use JDeveloper's JSF Navigation Diagram to plan and create your application's pages and to define the navigation between them when you work with more than one page. Also you will   use the dataTable ICEFaces component to show the data that comes from the model.

Importnat Note: The ICEFaces integration with JDeveloper doesn't work with the WYSIWYG editor that JDeveloper offers for JSF and JSP development. However you can still use the combination of the structure pane, component palette and property inspector to define your JSF. You can also use the code editor and enjoy the code insight and other coding features it offers for JSF developers.

To create the page, perform the following steps:

1.

Switch to the faces-congig.xml file and to diagram view of the file. Ensure that JSF Navigation Diagram is selected from the dropdown list of the Component Palette

Select JSF Page and click on the diagram in the position where you want the page to appear.

view05.jpg

Note that the page appears with a yellow warning symbol. This is because you have depicted a page on the diagram that does not yet exist. The yellow warning disappears later when you create the page.

 

2.

Rename the page departments by typing over the name.

view06.jpg

You need only to type the name; JDeveloper automatically adds the leading forward slash and the . jsp extension when you press [Enter]

Click Save All  to save your work.

3.

On the JSF Navigation Diagram, double-click departments.jsp to launch the Create JSF JSP wizard.

If the Welcome page of the wizard displays, click Next.

On the JSP File page of the wizard, for Type, select the JSP Document option. This creates an XML representation of a JSP page, ensuring that the page uses well-formed XML syntax.

view07.jpg

Click Next to continue.

4.

On the Component Binding page, select the Do Not Automatically Expose UI Components in a Managed Bean option. Leave other values as their defaults and click Next.

view08.jpg

5.

Ensure that the libraries shown below are in the Selected Libraries list.

        JSF Core 1.0
        JSF HTML 1.0
        ICEFaces Component Suite 1.5.3

view09.jpg

If they are not selected, select them in the Available Libraries list and click Add Add buttonto shuttle them to the Selected Libraries list. Note that the library version numbers may be different from those shown.

Click Next to accept the libraries that you need in order to create the ICEFaces components on your page.

6.

Click Next to accept the default HTML options, then click Finish to create the new JSF JSP.

view10.jpg

The empty departments.jspx page opens in the editor. In the next few steps, you add a data-bound ICEFaces dataTable component to the page. This component displays the departments.

 

7.

Click Save All  to save your work.

8.

Go back to Design view. Click in the blank screen.

Write as a Heading List of Departments Using JPA and ICEFaces

view12.jpg

 Now write some additional text

view13.jpg
Switch to the source view of your page to see the JSF source for the page you just modified visually.

9.

ICEFaces components use the ice:form component to encapsulate other components. We'll convert the h:form component to the right one.
From the structure pane, right click on the h:form component and choose Convert

Now select ICE Faces Components Suite from the drop down list of copmponents libraries, and choose Form as the component to convert to.

Click Save All  to save your work.

10.

Next, we'll use the component palette to add a data table to our page. In the component palette window (use ctrl+shift+p to bring it up) make sure you are watching the ICEFaces Components Suite set of component, and locate the datatable component.

Drag it from the component palette onto the ice:forms node in the structure pane window.

Next, click the datatable node in the structure window and use the property inspector window to set the following properties for the datatable component.

  • Border: 1
  • Id: depTable
  • Var: dep

position the cursor in the value property and click the bind to data button.

This will pop up the expression builder dialog. In the variables window, navigate to JSF Managed Beans - DepartmentBean - departments and shuttle it to the right, then click ok. This binds the table to the departments List that is returned from the managed bean we created before.


Next we'll add the columns to the datatable, while you can do it through the same drag and drop process, you might find it faster to just copy paste the following code. Remove the closing "/" from the the <ice:dataTable/> tag, go to the next line and type </ - this will cause JDeveloper to automatically complete the correct closing tag.
in between   < ice:dataTable></ ice:dataTable> add the following code:

            < ice:column>
                < f:facet name="header">
                    < ice:outputLabel value="Department ID"/>
                </ f:facet>
                < ice:outputText value="#{ dep.departmentId}"/>   
            </ ice:column>
            < ice:column>
                < f:facet name="header">
                    < ice:outputLabel value="Department Name"/>
                </ f:facet>
                < ice:outputText value="#{ dep.departmentName}"/>
            </ ice:column>
            < ice:column>
                < f:facet name="header">
                    < ice:outputLabel value="Department Location"/>
                </ f:facet>
                < ice:outputText value="#{ dep.locationId}"/>
            </ ice:column>

You should have something like this

Click Save All  to save your work

Back to Topic List

Running the Application

Now that you have built your new application, and you want to test it. JDeveloper makes it easy to test JSF/EJB applications through a built-in J2EE server. This OC4J server is automatically launched when you test a page from within JDeveloper.

To complete the testing process, perform the following steps.

1.

Right-click departments.jspx either in the Applications Navigator, the editor for that page, or the JSF Navigation Diagram, and select Run from the context menu.

view17.jpg

The embedded OC4J server starts and is initialized, and the page displays in a browser.

 

2.

See the result

view18.jpg

Tip - If you get an error stating javax.faces.FacesException: Failed to execute JSP lifecycle. Navigate to Web Content - WEB-INF and open the web.xml file. Locate the following entry in the file:

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

Replace the entry with the following:

    <servlet-mapping>
        <servlet-name>Persistent Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

Try running the page again now.

Back to Topic List

Adding Table Pagination

Now that you have you DataTable you are going to add pagination in order to display smaller amount of data. And this way you can see have direct interaction with AJAX events.

To add pagination to the table you just created, perform the following steps.

1.

Go to departments.jspx design editor. In the structure pane expand the  body structure and select  ice :dataTable Go to the inspector Pane and assign 5 to the Rows value.

pagination1.jpg

Click Save All  to save your work

2.

Go the departments.jspx source code and add the following code after </ ice:dataTable>

< ice:dataPaginator id="dataScroll_1" for=" depTable"
                                   paginator="true" paginatorMaxPages="5">
                    < f:facet name="first">
                        < ice:outputLabel value="First"/>
                    </ f:facet>
                    < f:facet name="next">
                        < ice:outputLabel value="Next"/>
                    </ f:facet>
                    < f:facet name="previous">
                        < ice:outputLabel value=" Prev"/>
                    </ f:facet>
                    < f:facet name="last">
                        < ice:outputLabel value="Last"/>
                    </ f:facet>
</ ice:dataPaginator>


It should look like this

pagination2.jpg

Click Save All  to save your work

 

3.

Right-click departments.jspx either in the Applications Navigator, the editor for that page, or the JSF Navigation Diagram, and select Run from the context menu.

See the Result

pagination3.jpg

4.

Finally add a navigation Range pagination in the footer of the table. Go to departments.jspx source editor and  after the last </ ice:column> before </ ice:dataTable> add a footer facet with the following code:

< f:facet name="footer">
                        < ice:dataPaginator id="dataScroll_2" for=" depTable"
                                           rowsCountVar=" rowsCount"
                                           displayedRowsCountVar=" displayedRowsCount"
                                           firstRowIndexVar=" firstRowIndex"
                                           lastRowIndexVar=" lastRowIndex"
                                           pageCountVar=" pageCount"
                                           pageIndexVar=" pageIndex">
                            < ice:outputFormat value="{2} to {3} of {0} departments found"
                                              styleClass="standard">
                                < f:param value="#{ rowsCount}"/>
                                < f:param value="#{ displayedRowsCount}"/>
                                < f:param value="#{ firstRowIndex}"/>
                                < f:param value="#{ lastRowIndex}"/>
                                < f:param value="#{ pageIndex}"/>
                                < f:param value="#{ pageCount}"/>
                            </ ice:outputFormat>
                        </ ice:dataPaginator>
</ f:facet>

Now your page should look like this:

pagination4.jpg

Click Save All  to save your work

5.

Right-click departments.jspx either in the Applications Navigator, the editor for that page, or the JSF Navigation Diagram, and select Run from the context menu.

See the Result

pagination5.jpg

Summary

In this tutorial, you created a simple end-to-end application by using JDeveloper, JPA/ Toplink Essentials, and ICEFaces. You learned how to:

Install the ICEFaces extension for JDeveloper and integrate ICEFaces with existing JSF projects

Use JPA and EJB to create the business model and session facade

Work with the jsf-config.xml file to create managed beans

Work with JSF and the ICEFaces components and bind them to data from JPA entities

Test the application inside JDeveloper

Further Information

false ,,,,,,,,,,,,,,,