28
Simplifying development of JSF Portlet Applications using JPA with Rational Application Developer 8.0 Charu Malhotra, Software Engineer, IBM Summary: This article explains how to create a simple end-to-end JPA enabled JSF CRUD portlet application using Portal Toolkit available in IBM® Rational® Application Developer Version 8.0. It also emphasizes how the toolkit available in RAD greatly simplifies the whole process to just a few clicks on the UI and a few drag and drops, thereby letting you quickly create the portlet application. Introduction The Java Persistence API was first developed as a part of the EJB 3.0 specification but it emerged as an independent specification which can be used in any Java EE environment. The JPA API simplifies object relational mapping and data persistence. While developing a JPA application a developer directly deals with the JPA entities which are object representations of database tables. It exposes methods to manage and persist JPA entities which save the developer from writing the backend JDBC code. JPA persistence also ensures application data is in synch with the current state of the database. Prerequisites IBM® Rational® Application Developer Version 8.0 IBM WebSphere Portal Next Server Sample application description In this article we will quickly build a simple portlet application using the below tools: RAD Portal Toolkit Java™ Persistence API (JPA) tools to access a database We will use Rational Application Developer to achieve the following tasks: Create a portlet application targeted to a portal server.

Simplifying development of JSF Portlet Applications using JPA w - IBM

  • Upload
    dothien

  • View
    233

  • Download
    5

Embed Size (px)

Citation preview

Page 1: Simplifying development of JSF Portlet Applications using JPA w - IBM

Simplifying development of JSF PortletApplications using JPA with RationalApplication Developer 8.0Charu Malhotra, Software Engineer, IBM

Summary: This article explains how to create a simple end-to-end JPA enabled JSFCRUD portlet application using Portal Toolkit available in IBM® Rational® ApplicationDeveloper Version 8.0. It also emphasizes how the toolkit available in RAD greatlysimplifies the whole process to just a few clicks on the UI and a few drag and drops,thereby letting you quickly create the portlet application.

IntroductionThe Java Persistence API was first developed as a part of the EJB 3.0 specification but itemerged as an independent specification which can be used in any Java EE environment.The JPA API simplifies object relational mapping and data persistence. While developinga JPA application a developer directly deals with the JPA entities which are objectrepresentations of database tables. It exposes methods to manage and persist JPA entitieswhich save the developer from writing the backend JDBC code. JPA persistence alsoensures application data is in synch with the current state of the database.

Prerequisites

IBM® Rational® Application Developer Version 8.0

IBM WebSphere Portal Next Server

Sample application descriptionIn this article we will quickly build a simple portlet application using the below tools:

RAD Portal Toolkit

Java™ Persistence API (JPA) tools to access a database

We will use Rational Application Developer to achieve the following tasks:

Create a portlet application targeted to a portal server.

Page 2: Simplifying development of JSF Portlet Applications using JPA w - IBM

Create a database connection from the database development view. For this articlewe would be using the DB2 SAMPLE database.

Generate JPA manager beans and JPA entities. This will also install the JPA 1.0facet and handle JPA configuration and database configuration tasks for us.

Consume the JPA data in portlet jsp pages to create a simple CRUD JSFapplication.

Building the sample application

Portlet project and portlet creation

Create a new portlet project as shown in Figure 1.

1. Select File > New > Portlet Project

2. Enter InventoryPortlet as the Portlet Project Name. In the Portlet settingsgroup, Create a portlet checkbox is checked by default. This also creates aportlet named InventoryPortlet inside the InventoryPortlet project. You canspecify a different name for the portlet in the Portlet name text box.

3. Select WebSphere Portal Next as the Target Runtime. Refer Figure1 below.

Page 3: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure1: New Portlet Project Wizard

4. Click Modify… button beside Configuration and select JSR 286 as the APIand Faces as the Portlet Type from the Portlet Project Configuration dialogshown in Figure 2. Click OK.

Page 4: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure2: Create JSR286 Faces portlet project

5. The Portlet Project wizard is back in focus again. Accept the default settingsfor the remaining fields on the New Portlet Project wizard and click Finish.

6. When prompted, switch to the Web perspective.

A portlet project and the corresponding EAR are created and appear in the EnterpriseExplorer view.

The wizard also creates a portlet named InventoryPortlet in the InventoryPortlet project.

Establishing the database connection

1. Open Database Development perspective.

Page 5: Simplifying development of JSF Portlet Applications using JPA w - IBM

2. Right-click Database Connections in Data Source Explorer view and selectNew.

3. New Connection wizard opens, select DB2 as database manager.

4. Select IBM Data Server for JDBC and SQLJ as JDBC driver.

5. Enter the required database properties in the New Connection wizard asshown in Figure 3. Enter DB2 user name and password. Also select thecheckbox to save DB2 password and test the connection.

Figure3: Specify driver properties

Page 6: Simplifying development of JSF Portlet Applications using JPA w - IBM

6. Click Finish.

Figure4: DB2 SAMPLE database connected

If you want to use a different database you can create one using New Connection wizard.Ensure that the connection is up and go back to the Web perspective to create the JPAentities.

JPA Entities and Manager Beans creationRAD JPA tools help you to quickly create JPA entities and manager beans with fewclicks on the wizards.

Create the JPA entities

1. Right-click the Portlet project created above (InventoryPortlet) in theEnterprise Explorer view, and choose JPA Tools > Configure JPAEntities… as shown in Figure 5.

Page 7: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure5: Launch Configure JPA Entities WizardFigure5: Launch Configure JPA Entities Wizard

2. Launching the Configure JPA Entities… wizard automatically installs theJPA 1.0 facet if it is not installed already.

Page 8: Simplifying development of JSF Portlet Applications using JPA w - IBM

3. After the facet is installed the Configure JPA Entities wizard comes up.Click the Create New JPA Entities button to launch the Generate CustomEntities wizard. Refer Figure 6.

Figure6: Create New JPA Entities

4. Select the SAMPLE database and the ADMINISTRATOR schema, asshown in Figure 7.

Page 9: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure7: Generate Custom Entities

Page 10: Simplifying development of JSF Portlet Applications using JPA w - IBM

5. Select the INVENTORY table and click Finish. This creates the inventoryentity. Refer Figure 7 above.

6. In order to configure this entity, select the Inventory Entity on the ConfigureJPA Entities wizard which is back in focus again and click next as shown inFigure 8 below.

Figure8: Configure JPA Entities

Page 11: Simplifying development of JSF Portlet Applications using JPA w - IBM

7. On the Tasks page ensure Inventory entity has a primary key.

8. Click the other tab and choose to add an equals and hash Code method if notpresent and press finish. Refer Figure 9 below.

Figure9: Select Primary Key

NOTE: The JPA Facet can also be enabled from the project facet page. Adding the JPAfacet will create JPA configuration.xml files (persistence.xml) in the java source META-INF folder. It also creates a top-level JPA Content node that provides quick access to thePersistence XML Editor.

In addition to generating JPA entities the above steps also perform database and JPAconfiguration tasks. They configure the data source in the persistence.xml file. And also

Page 12: Simplifying development of JSF Portlet Applications using JPA w - IBM

set the database connection information on the Deployment tab of the EAR's WebSphereDeployment Descriptor for use during runtime.

Create JPA Manager Beans

JPA Manager Beans are a concept introduced by Rational Application Developer. Theyperform the business logic related to an entity. They also handle the JPA-specificpersistence tasks for us and help us access the database and manage entities effectively.The JPA manager bean wizard provides several options to auto-generate JPA queries and define relationships in the database.

We will now create the JPA Manager bean (InventoryManager bean) for the InventoryEntity.

1. Right-click the Portlet project created above in the Enterprise Explorer view,and choose JPA Tools > Add JPA Manager beans… Refer Figure 10.

Page 13: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure10: Launch JPA Manager Bean Wizard

2. Choose the Inventory Entity from the list of available entities as shown inFigure 11.

Page 14: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure11: Create Inventory Manager Bean

3. Click Next and click the hyperlink Launch Entity Configuration Wizard asshown below

Page 15: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure12: Launch Entity Configuration Wizard

4. Now we will add a named query getInventory to the InventoryManager bean.On the Configure JPA Entities dialog select Named Queries task and clickAdd to open Add Named Query dialog as shown in the Figure 13 below.

Page 16: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure13: Launch Add Named Query Dialog

5. On Add Named Query dialog you can edit the getInventory built-in query. Bymaking selections on this dialog you can select different result attributes andalso filter and order results as per your requirement. Refer Figure 14.

Page 17: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure14: Add Named Query

6. For this exercise select pid field on the Order Results tab to order the resultsby pid as shown in Figure 15 below.

Page 18: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure15: Order Query Results

7. Click OK on Add Named Query dialog and press Finish on the Add JPAManager Bean Wizard.

The Inventory JPA entity and InventoryManager bean have now been created. Notice thatthe entity is created in the src/entities directory and the manager bean in src/entities/controller directory. The Inventory entity is the class representation of the Inventory tablewith the table columns represented by the class fields.

Page 19: Simplifying development of JSF Portlet Applications using JPA w - IBM

The InventoryManager contains the get Inventory method that was generated by the JPAManager bean wizard.

JPA data consumptionJPA integrates well with JSF portlet applications. JPA data can be very easily consumedin JavaServer Faces Web pages in a JSF portlet application, without writing any piece ofcode. We can achieve this by simple drag and drops on the portlet jsp pages from pagedata view.

1. Open the InventoryPortletView.jsp in Page Designer in design view

2. From the Page Data view expand JPA->JPA Manager Beans and select thegetInventory query as shown in Figure16 below.

Figure16: DND from Page Data View

3. Drag and drop getInventory from page data view on InventoryPortletView.jspopened in Page Designer. Add JPA data to page wizard comes up as shownin the Figure 17 below.

Page 20: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure17: Display Inventory list

4. From the wizard choose the radio button Retrieve a list of data and pressNext.

5. Order the fields as per your requirement and click Finish.

6. The code to display Inventory list is auto-generated in theInventoryPortletView.jsp. Press Ctrl+S to save.

Publishing to WPNext serverSo far we have created an end-to-end JPA enabled portlet application which displays alist of Inventories fetched from the back-end database. All this has been done withoutwriting a single line of code and with just a few clicks on the wizardsOur JSF portlet project is now ready to be published to the portal server.

Page 21: Simplifying development of JSF Portlet Applications using JPA w - IBM

1. Right-click the InventoryPortlet project and select Run As > Run on Server

2. Select WebSphere Portal Next from the list and press Finish.

Figure18: Publish on server

CRUD application completion

We will now see how this application can be very quickly enhanced to turn it into aCRUD application

Note: There can be different ways to navigate between different web pages and storeparameter values in a JSF application; we are just showing one of them as an illustration.In this article we will make use of command links and request parameters for the same.

1. Create 3 new Portlet jsps- displayInventory.jsp, updateInventory.jsp, andcreateInventory.jsp

2. To create a jsp right-click the portlet project in the Enterprise Explorer view andchoose New->WebPage

3. Open displayInventory.jsp and from the Page Data view expand JPA->JPAManager Beans. Drag and drop findInventoryByPid query from Page Data viewon displayInventory.jsp opened in Page Designer. Add JPA data to page wizardcomes up, refer Figure 19. Press Next and press Finish. Save changes made todisplayInventory.jsp

Page 22: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure19: Display Inventory details

4. This adds the code to display inventory details of a particular product specified bythe parameter “pid”.

5. Now again open InventoryPortletView.jsp. We will update this jsp file so thatwhen a particular pid is clicked on InventoryPortletView.jsp, its details are shownon displayInventory.jsp.

Add a command Link around the pid column of the auto generated inventoryList tableand also add a request param to store the pid value as shown by the code snippet below;

<h:commandLink id="link1" styleClass="commandLink"><h:outputText styleClass="outputText" id="pid1"value="#{varinventoryList.pid}"></h:outputText>

<f:param name="pid" value="#{varinventoryList.pid}"></f:param> </h:commandLink>

Note: Make sure the command link is enclosed in a form.

Page 23: Simplifying development of JSF Portlet Applications using JPA w - IBM

6. Select the above command link and open properties view.

7. Open Quick Edit view and code an action for the command link

8. Add the below code to the generated action

ActionResponse response = (ActionResponse)getFacesContext().getExternalContext().getResponse();response.setRenderParameter("pid",(String)getRequestParam().get("pid");return "display";

9. From the properties view add a navigation rule to open displayInventory.jsp whenaction outcome “display” is triggered from InventoryPortletView.jsp

Figure20: Add Navigation Rule for InventoryPortletView.jsp

10. Similarly in order to open an inventory item in edit mode when it’s selected indisplayInventory.jsp

11. Open displayInventory.jsp and add a command Link around the pid column and arequest param to store the pid value. The code inserted would be similar to thecode snippet shown below:

<h:commandLink id="link1" styleClass="commandLink"> <h:outputText styleClass="outputText" id="pid1"value="#{pc_DisplayInventory.inventory.pid}">

</h:outputText> <f:param name="pid" value="#{pc_DisplayInventory.inventory.pid}"></f:param>

</h:commandLink>

12. Select the above command link and open properties view.

13. Open Quick edit view and code an action for the command link

Page 24: Simplifying development of JSF Portlet Applications using JPA w - IBM

14. Add the below code to the generated action

ActionResponse response = (ActionResponse)getFacesContext().getExternalContext().getResponse();response.setRenderParameter("pid",(String)getRequestParam().get("pid");return "update";

15. From the properties view add navigation rule to open updateInventory.jsp whenaction outcome is update. Refer Figure 21.

Figure21: Add Navigation Rule for displayInventory.jsp

16. Now open updateInventory.jsp and drag and drop query updateInventory frompage data view on the updateInventory.jsp opened in Page Designer. Add JPAdata to page wizard comes up. The wizard shows “pid” as the filter parameter,press Next and press Finish.

This will add two auto-generated actions updateInventoryAction anddeleteInventoryAction to updateInventory.jsp. Two new command buttons Submit (forupdateInventoryAction) and Delete (for deleteInventoryAction) are added to theupdateInventory.jsp along with the code to update or delete the displayed inventory item.You can define the navigation rules and return the appropriate outcomes from these twoauto generated actions.For instance you can return the outcome “view” and define the navigation rule as shownin Figure 22 below.

Figure22: Add Navigation Rule for updateInventory.jsp

Page 25: Simplifying development of JSF Portlet Applications using JPA w - IBM

17. Finally DND createInventory query from page data view on createInventory.jspopened in Page Designer. This adds the code to create a new inventory item in theInventory table.

Publishing the complete application to WPNext serverPublish the final CRUD application on the server.

Right-click the InventoryPortlet project and select Run As > Run on Server

Select WebSphere Portal Next from the list and click Finish.

Page 26: Simplifying development of JSF Portlet Applications using JPA w - IBM

Figure23: Publish the CRUD Application

What have we learnedIn this article we saw how Rational Application Developer 8.0 makes it easy to build JPAJSF portlet applications. We reviewed JPA concepts and saw how it makes database

Page 27: Simplifying development of JSF Portlet Applications using JPA w - IBM

management easy for the developer and frees him from database persistence tasks. Thearticle also introduced us to JPA configuration and database configuration tasks which areautomatically handled for us in Rational Application Developer 8.0 along with auto-generated JPA entities and manager beans. We also used the query builder which auto-generates JPA queries for us. Finally Portal Toolkit and JPA tools helped us easily build aJPA portlet application with few clicks on the wizards and simple drag and drops,without writing a lot of code.

Application sample for downloadThe InventoryPortlet sample application created in this article is available for downloadfor your reference.

Setup instructions.Follow these steps to set-up the application sample in RAD:

1. Import the InventoryProject.zip file, Select File->Import->Existing Projects intoworkspace.

2. Open Database Development perspective.

3. Right-click Database Connections in Data Source Explorer view and select New.

4. New Connection wizard opens, select DB2 as database manager.

5. Select IBM Data Server for JDBC and SQLJ as JDBC driver.

6. Enter the required database properties in the New Connection wizard as shown inFigure 3 above. Enter DB2 user name and password. Also select the checkbox tosave DB2 password and test the connection. Click Finish.

7. Open Web perspective and in Enterprise Explorer right-click the InventoryPortletProject.

8. Select JPA Tools-> Configure Project for JDBC Deployment -> SAMPLE inConnection drop-down and click Finish.

Page 28: Simplifying development of JSF Portlet Applications using JPA w - IBM

9. To publish the application on server right-click InventoryPortlet and select Run as> Run on Server.

10. Select WebSphere Portal 7 and click Finish.