Legal | Privacy
Build a Web Application with JDeveloper 11g Using EJB, JPA, and JavaServer Faces

Build a Web Application with JDeveloper 11g Using EJB, JPA, and JavaServer Faces

In this tutorial, you use Oracle JDeveloper 11g to build a web application. To build the data model, you use the EJB diagrammer, utilizing EJB 3.0 and Java Persistence API (JPA). For the web client, JavaServer Faces (JSF) is used. A master-detail page and an edit page will be included in the user interface.

1 hour

Topics

The tutorial covers the following topics:

Building the Data Model using EJB 3.0

Creating a New Project for the User Interface

Creating the Page Flow

Creating a Master-Detail JSF Page

Creating a Query Page

Running the JSF Pages

Place the cursor over this icon to load and view all the screenshots for this tutorial. (Caution: This action loads all screenshots simultaneously, so response time may be slow depending on your Internet connection.)

Note: Alternatively, you can place the cursor over an individual icon in the following steps to load and view only the screenshot associated with that step. You can hide an individual screenshot by clicking it.

Overview

The application reflects the Model-View-Controller architecture. The model is provided by EJB Components, while the view and controller are provided by JavaServer Faces.We will be using the ADF Faces set of JSF-compatible components to build a richer web interface.

You will first build the data model portion of the application. The Java Persistence API (JPA) provides a POJO persistence model for object-relational mapping. The Java Persistence API was developed by the EJB 3.0 software expert group as part of JSR 220, but its use is not limited to EJB software components. It can also be used directly by web applications and application clients, and even outside the Java EE platform, for example, in Java SE applications.

Enterprise JavaBeans (EJB) technology is the server-side component architecture for Java Platform, Enterprise Edition (Java EE) that encapsulates business logic. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology.

The Java Persistence API is the standard API for the management of persistence and object/relational mapping. It provides an object/relational mapping facility for application developers using a Java domain model to manage a relational database. The Java Persistence API is part of the Java EE platform. It can also be used in Java SE environments.

In the tutorial, you implement a persistence model by developing Session and Entity beans. These beans use the EJB 3.0 annotations and JPA for model persistence.

  • EJB 3.0 entities represent persistent data from the database, such as a row in a customer table or an employee record in an employee table. Entities are also sharable across multiple clients. You use the Entity Manager API to create, update, delete and query the persistence model.
  • Session beans perform a distinct, decoupled task such as checking credit history for a customer.

You will then create a master-detail form for viewing Departments and Employees information. Following this basic master-detail page creation, you will create an edit page for the selected employee.

While developing and testing the application, you will use JDeveloper's embedded Java EE application server.

Back to Topic List

You need to create persistence objects for the DEPARTMENTS and EMPLOYEES tables. The persistence objects are implemented as Entity Beans. Default getter and setter methods are created for department and employee data. These methods are implemented as part of a session bean. Then you create a Master Detail JSF page based on Department and related Employees, and an Edit JSF page allowing the update of employee's data.

Back to Topic List

Prerequisites

Before starting the tutorial, you should:

1.

Have access to or have installed Oracle JDeveloper 11g (TP4). You can download it from Oracle Technology Network.

 

2.

Have access to or have installed Oracle Database 10g (Release 2 or Release 1). You can download it from Oracle Technology Network (http://www.oracle.com/technology/software/products/database/oracle10g/index.html).

Alternatively, you can install the free Oracle XE database. You can download it from Oracle Technology Network ( http://www.oracle.com/technology/products/database/xe/index.html).

 

3.

Have access to or have installed the Oracle Sample Schemas, included with Oracle Database 10g.

The tutorial uses the HR schema. Specifically, the pages work with the DEPARTMENTS and EMPLOYEES tables.

Instructions for installing the HR schema and creating a connection to it in JDeveloper are available online at:

http://www.oracle.com/technology/obe/obe1013jdev/common/OBEConnection.htm

4.

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

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

If prompted for a User Role, choose Default.

Close the Tip of the Day window.

 

5.

The JDeveloper IDE should now be displayed.

Back to Topic List

Creating a Database Connection

Java Database Connectivity (JDBC) is a standard API that is used for connecting a Java application to relational databases. JDeveloper uses a connection navigator to maintain connection information for your application. The connection navigator makes it easy to create, manage, and test database connections.

If you haven't already established a connection to the database, then do so by performing the following steps:

1.

Click the Database Navigator tab on the Application Navigator. If the Database Navigator tab is not showing, choose View > Database Navigator from the JDeveloper main menu.

 

2.

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

3.

In the Create Database Connection Dialog, in the first section enter the following values:

Connection Name HRConn
Connection Type Oracle JDBC
Username hr
Password hr
Save Password (checked)
Deploy Password (checked)

Note: It is secure to deploy the password since it gets encrypted.

In the Oracle (JDBC) Settings section, enter the following values:

Driver thin
Host Name localhost
JDBC Port 1521

Choose the solution that applies best to your environment by completing one of the 2 following lines:

SID orcl
Service Name XE

 

4.

Click Test Connection.

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

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

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

 

5.

The Database Navigator should look like this:

 

 

You have just created a connection to the database that will supply data for the application you build in this tutorial.

The next section uses this connection.

Back to Topic List

Building the Data Model with EJB 3.0 Using the EJB Diagramer

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

In the next few steps, you create an application in JDeveloper and create a data model for your application.

Back to Topic List

Create a New Application and Project

In JDeveloper, you always work with projects contained in an application. The application is the highest point in the control structure.

A JDeveloper project is an organization structure used to logically group related files You can add multiple projects to your application to easily organize, access, modify, and reuse your source code. In the Application Navigator, projects are displayed as the second level in the hierarchy, under the application.

It is considered best practice to use projects to separate the model code from the code written for the view. In this tutorial, we will create one project for the EJB Components model, and later on a second one for the JSF views.

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

1.

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

Click the New Application icon.

2.

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

Enter oracle as the Application Package Prefix.

Select the No Template [All Technologies] value from the Application Template drop-down list.

Click OK.

3.

In the Create Project dialog, set Project Name to EJBModel then OK.

 

4.

In the Navigator pane, click the Databases tab.

 

5.

Select the HRConn connection in the IDE connections list and drag and drop it inside the HR_EJB_JPA_App node to make the connection available for your application.

 

  Click the Application Navigator tab.

Back to Topic

Back to Topic List

Creating the Persistence Model

In this section of the tutorial, you create the persistence model for departments and employees using EJB 3.0 entity beans.

To create EJB 3.0 entity beans, perform the following steps:

1.

In the Application Navigator, right click the EJBModel node and select New from context.

 

2.

In the New Gallery select the All Technologies tab, then select Business Tier | EJB as the category and double click the Entities from Tables item.

 

3.

In the Create Entities from Tables wizard, if necessary, click Next to skip the Welcome page.

 

4.

In Select EJB Version, select EJB 3.0 -- JPA Entities as the EJB version, then Next.

 

5.

In the click Next to skip the persistence unit definition.

 

6.

In the Type of Connection choose the Online Database Connection option and accept the default Offline Database name, then Next.

 

7.

In the Database Connections Details, select HRConn as the connection to use.

Click Next

 

8.

Press the Query button to retrieve the available objects for the HR schema. Then select DEPARTMENTS and EMPLOYEES and shuttle the selection in the selected pane using the right arrow button .

Click Next.

 

9.

In this step, make sure the package name is oracle.

Click Next, then Finish.

 

10.

In the Application Navigator one java file is created for Departments and one for Employees.

 

11.

Right click the EJBModel node in the Application Navigator and select New from context.

 

12.

In the New Gallery select Business Tier | EJB as the category and double click the EJB Diagram (JPA/EJB 3.0) item.

Click OK.

 

13.

In the Create EJB Diagram dialog, change the default name for the diagram (EJB Diagram1) to EJB 3 and verify oracle is the Package name.

Click OK.

On the Associate Diagram With Persistence Unit dialog, click OK to accept the proposed Persistence Unit EJBModel (EJBModel.jpr).

Click OK on the EJB Modeler information dialog.

 

14.

A new empty diagram opens in the diagram editor.

 

15.

Select the Departments and Employees entities from the Application Navigator then drag and drop the selection onto the diagram.

 

16.

The diagram displays the EJB components that correspond to the Reverse Engineering action you previously performed on Departments and Employees. Reorganize the layout of the diagram to have both entities horizontally aligned.

 

17.

Click the save all icon to save your work.

 

Back to Topic

Back to Topic List

Creating the Data Model and Testing it

A session facade presents client objects with a unified interface to the underlying EJBs (Enterprise JavaBeans). The client interacts only with the facade, which resides on the server and invokes the appropriate EJB methods. As a result, dependencies and communication between clients and EJBs are reduced.
If you are performing remote access without a session facade, numerous remote calls are needed for the clients to access EJB 3.0 entities directly over the network. This results in a large amount of network traffic that negatively affects performance. In addition, without a facade the client depends directly on the implementation of the business objects, so that if the interface of an EJB changes, client objects have to be changed as well.

In this section, you create a session bean that implements a method to find employee and department records.

1.

In the Component Palette, select the EJB Components library and open the EJB Nodes.

 

2.

Select the Session Bean component then drag and drop it onto the diagram.

The Create Session Bean Wizard opens. If necessary, click Next on the Welcome step.

 

3.

In the EJB Name and Options step, set the EJB Name to HRFacade and make sure that the following values are properly set:

Session Type Stateless
Transaction Type Container
Generate Session Facade Method (Checked)
Entity Implementation JPA Entities
Persistence Unit EJBModel

then click Next.

 

4.

In the Session Facade step, any entities in this project appear as a node in the tree control. You can select the checkbox to include all entity methods this entity exposes, or expand the nodes and select a subset of methods.
Expand the Employees and Departments nodes and deselect the findAllByRange method for each entity, then click Next.

 

5.

In the Class Definition step, make sure that the full name for Bean Class is oracle.HRFacadeBean, and then click Next.

 

6.

In the following step, have both Remote and Local interface implementation selected. The remote interface is used for client applications that run in a separate virtual machine, such as Java clients whereas local interface is used for client applications that run in the same virtual machine, such as Web clients .

Click Next to review the summary of the created classes and then Finish.

 

7.

The Application Navigator should look like this:

The session bean is made up of three files: HRFacadeBean - contains the session bean code. HRFacade - describes the capabilities of the bean for remote clients and HRFacadeLocal describes the capabilities for the local client.

 

8.

Double click the Employees entity bean on the diagram to open the source code for the class.

 

9.

Named queries enable you to define queries at design time and then use them at run time. Two NamedQuery metadata statement have been created by default. One retrieves all rows from the employees table, the second one counts the number rows for the table.

@NamedQuery(name = "Employees.findAll", query = "select o from Employees o"),
@NamedQuery(name = "Employees.findAll.size", query = "select count(o) from Employees o")

Note: Any symbol in Java code beginning with @ is known as an annotation. The use of annotations allows you to add metadata to your objects. Examples of annotations follow:

Annotation Description
@Entity Identifies the file as an EJB 3.0 entity
@NamedQuery A query that can be used at run time to retrieve data
@Table Specifies the primary table for the entity
@Id Can define which property is the identifier for the entity
@Column Specifies a mapped column for a persistent property or field
@ManyToOne Specifies a type of foreign key relationship between tables
@JoinColumn Specifies the join column and referenced column for a foreign key relationship

 

10.

Add a coma at the end of the last @NamedQuery statement, then add a query to the class that retrieves employees by name.

Add the following statement:
,
@NamedQuery(name = "Employees.findByName", query = "select o from Employees o where o.firstName like :p_name")

So that the code looks like the following:

@Entity
@NamedQueries({
@NamedQuery(name = "Employees.findAll", query = "select o from Employees o"),
@NamedQuery(name = "Employees.findAll.size", query = "select count(o) from Employees o")
,
@NamedQuery(name = "Employees.findByName", query = "select o from Employees o where o.firstName like :p_name")
})

If required, use the ALT + Enter keystroke combination to import the javax.persistence.NamedQueries library.

Note: What makes these objects different from other Java files are the annotations that identify them as EJB entities. A key feature of EJB 3.0 and JPA is the ability to create entities that contain object-relational mappings by using metadata annotations rather than deployment descriptors as in earlier versions.

 

11.

Click the Make icon to compile the Employees.java class.

Make sure that the Message - Log window does not report any error.

 

12.

Add the new method to the session bean doing the following:

Right click the HRFacadeBean node in the Application Navigator and select Edit Session Facade from context.

 

13.

Expand the Employees node of the dialog. Notice that the new named query Employees.findByName appears as exposable method. Select it and OK.

 

14.

JDeveloper provides a way to test the EJB by creating a sample client. To do so, right click HRFacadeBean and select New Sample Java Client from context.

 

15.

Select the Connect to OC4J Embedded in JDeveloper option.

Click OK.

 

16.

Review the code of the HRFacadeClient class and correct the reported error for the queryEmployeesFindByName() method and add a value parameter "P%" so that it looks like the following:

Click the save all icon to save your work.

 

17.

Right click the EJBModel project node in the Applications Navigator and select Project Properties from context.

 

18.

In the Project Properties dialog, select the Run/Debug/Profile node and make sure the Run Configuration is set to Default. (if not, double click the Default option, to open the Edit Run Configuration dialog and click OK to accept default values)

Click OK.

 

19.

Right click the HRFacadeBean in the Application Navigator and select Run from context to launch the facade bean in the Embedded OC4J sever.

Wait until the Embedded OC4J Server is started.

 

20.

Right click HRFacadeClient and select Run from context.

 

21.

The Log window returns the database data based on the three methods the client contains.

 

22.

To better visualize the result of the FindByName method, in the HRFacadeClient java class, comment out the for loop corresponding to the queryEmployeesFindAll() method, and comment out the for loop corresponding to the queryDepartmentsFindAll() method. Your code should look something like this:

 

23.

Click the Make button to recompile the class, and ensure that no errors are returned.

 

24.

Right click the HRFacadeClient class and select Run from context.

 

25.

The Log window should now display the returned rows retrieved by your ' P%' clause.

 

Back to Topic

Back to Topic List

Running the Java Service outside Java EE container

A persistence unit can be configured to run inside or outside the container. In EJB 3.0, you can run entities in a pure Java SE environment, without using an application server. One reason you might do this is to create a simple Java SE testbed (using JUnit, perhaps) to test your entity behavior without the overhead of deploying/executing in an application server. Another reason is you may want to run a Swing application locally.

In this section, you create a session bean that implements a method to find employee and department records.

1.

Let's now create a new persistence unit to run the java service outside the Java EE container.

Right click the META-INF | persistence.xml and select New Java Service Facade from context.

 

2.

In the Create Java Service Facade, click the New Unit button next to the Persistence Unit field.

 

3.

Set the Persistence Unit field to outside, make sure the JDBC connection is set to HRConn and the configure to run is Outside Java EE container.

Click OK.

 

4.

Back in the Create Java Service wizard, select the Generate a main() method checkbox.

Click Next.

 

5.

All methods should be selected by default. Deselect some of them so that your selection looks like the following image.

Click Next then Finish.

 

6.

In the source editor window, for the JavaServiceFacade class, add a new line after the // TODO comment and enter the following statement:

Employees a = javaServiceFacade.queryEmployeesFindByName("P%").get(0);

notice that you can use code coach to help you typing the syntax (CTRL + space bar)

Add this second statement using the short sop syntax standing for System.out.print and choose println() from the list then include a.getLastName() so that your class now looks like the following:

// TODO
Employees a = javaServiceFacade.queryEmployeesFindByName("P%").get(0);
System.out.println(a.getLastName());

 

7.

Click the Make button to compile the class and save you work.

 

8.

Right click the JavaServiceFacade node in the Application Navigator and select Run from context.

 

9.

The log window displays the result of the execution of the class running outside Java EE container, returning the first lastName of the retrieved records.

 

10.

Double click the META-INF | persistence.xml node to display the content of the file.

 

11.

Both persistence units are described. The default inside one and the newly created for outside Java EE run. Use the Source view to review details.

 

12.

We are now going to expose the EJB as a data control for the Oracle ADF framework. This will simplify the way that we can bind user interfaces to the EJB. To learn more about the ADF Framework visit:
http://oracle.com/technology/products/adf

Right-click the HRFacadeBean node in the Application Navigator and select Create Data Controls from context.

 

13.

In the Choose EJB Interface dialog, select Local, and click OK.

Click the Save All icon to save your work.

 

14.

The Application Navigator should now look like this:

 

15. You can collapse the EJBModel project node.

Back to Topic

Back to Topic List

Create a New Project for the User Interface

Because it is considered best practice to use projects to separate the model code from the code written for the view, since we've created the project for the EJB Components model, we now create a second one for the JSF views.

To do this, perform the following steps:

1.

On the application name bar, click the Application Menu icon

select New Project from context.

2.

In the New Gallery, select the Empty Project item.

Click OK.

3.

In the Create Project dialog, set Project Name to UserInterface then OK.

 

4.

In the Application Navigator, right click the UserInterface node and select Project Properties from context.

 

5.

In the Project Properties dialog, select the JSP Tag Libraries node. Select Distributed libraries then press the Add button.

 

6.

In the Tag Libraries list, select ADF Faces Components 11-ji3.

Click OK.

 

7.

Back in the Project Properties dialog, select the Technology scope node. In the Available technologies list, pick the JSF one and using the right arrow button , shuttle it in the Selected Technologies window. Notice that selecting JSF automatically propagates the required associated technologies (Java - JSP and Servlets)

Click OK.
Click the save all icon to save your work.

 

8.

The Application Navigator should now look like this:

 

Back to Topic List

Creating the Page Flow

You are going to use JDeveloper's JSF Navigation Modeler to diagrammatically plan and create your application's pages, and the navigation between them.

1.

In the Application Navigator, double click the UserInterface | Web Content | WEB_INF | faces-config.xml node to open a page flow diagram.

2.

The empty diagram opens. Notice the Component Palette to the right of the diagram editor. You use this to create components for the JSF Navigation Model.


3.

In the JSF Navigation Diagram page of the Component Palette, select JSF Page , and click where you want the page to appear on the diagram. Rename the page browse

4.

From the Component Palette, drag and drop a JSF Page next to the previous one. Rename the page query.

5.

Select JSF Navigation Case in the Component Palette. Click the icon for the source JSF page (browse), and then click the icon for the destination JSF page (query) for the navigation case.


6.

Modify the default label, 'success', by clicking it and typing query over it.

7.

JDeveloper gives you three views of the faces-config.xml file. We used the diagram view, but the same information is also accessible through a declarative dialog as well as the source directly.

Click the Overview tab at the bottom of the screen. Click Navigation Rules in the left-hand table to display existing Navigation Rules.

Click now the Source tab at the bottom of the screen. The <from-view-id> tag identifies the source page, and the <to-view-id> tag identifies the destination page.

 

8.

Click the Diagram tab to switch back to the diagram view, and select JSF Navigation Case in the Component Palette. Click the icon for the source JSF page (query), and then click the icon for the destination JSF page (browse) for the navigation case.

 

9.

Modify the default label, 'success', by clicking it and typing browse over it.

 

10.

Your diagram should now look something like the image below.

 

11. Click the save all icon to save the diagram.

Back to Topic List

Creating a Master-Detail JavaServer Faces Page

In the next few steps, you create an ADF Faces for the Department Employees Master Detail page.

1.

On the Page Flow diagram, double-click the browse icon to launch the Create JSF JSP wizard.

2.

The File name should be browse.jspx, select the Create as XML Document option.

Click OK.

You now have an empty browse.jspx page. In the next few steps, you add a data-bound ADF Faces component to the page. This component displays a department along with the employees belonging to this department.

 

3.

From the Component palette, for the ADF Faces library, select the layout section and drag a Panel Stretch Layout component onto the page


4.

From the Component palette, drag a Panel Splitter component on the middle of the page. (the cursor should be on the left of the center tag)

 

5.

Open the Data Controls component and expand the following nodes HRFacadeLocal | queryDepartmentsFindAll then drag and drop the Departments node within the first facet.

In the pop up menu, select Forms | ADF Read-only Form

 

6.

In the Edit Form Fields, check the Include Navigation Controls option

Click OK.

 

7.

In the Data Controls, expand the Departments node, select the employeesList node and drop it in the second facet.

In the pop up menu, select Tables | ADF Read-only Table

 

8.

In the Edit Table Columns dialog delete all columns except the following ones:
commissionPct,
email,
employeeId,
firstName,
hiredate,
jobId,
lastName,
phoneNumber,
salary,

and select Row Selection, and Sorting options.

Click OK.

The page should now look like this:


9.

In the Structure pane, select the af:panelSplitter pane and in the Property Inspector, set the Orientation to vertical.


10.

Select the af:panelStretchLayout tag and using the Property Inspector, for the Style | Box tabs set the Width to 600 Pixel and the Height to 400 Pixel so that the Employees table appears in the layout editor.

Select the af:table tag in the second pane and using the Property Inspector, for the Style | Box tabs set the Width to 100 Pct and the Height to 100 Pct.


11.

Reduce the height of the Department block.

 

12.

From the Component Palette, in the Common Components, select the Panel Menu Bar component and drop it onto the Facet Top tag, in the Design of the page.

13.

Click the Menu component then drag and drop it inside the Menu Bar.

14.

In the Property Inspector change the Text from menu 1 to Options.

 

15.

Click the Behavior tab and set the Detachable field to true.

 

16.

In the Structure Pane, right click the af:menu tag and from context select Insert Inside af:menu | MenuItem.

 

17.

In the Property Inspector, using the Common tab, change the Text to Query and from the drop down list set the Action to query.

 

18. Click the save all icon to save your work.

Back to Topic List

Creating a Query and Edit Page

In the next few ste