This article revisits one published by IBM® developerWorks® in 2010, "Create bottom-up JPA entities with Rational Application Developer, DB2, and WebSphere Application Server" (cited in Resources) by updating the discussion and instructions for these applications:
- IBM® Rational® Application Developer version 8.0.2 development environment
- IBM® WebSphere® Application Server version 8.0 beta (targeting the newly released Java Enterprise Edition (JEE) 6.0 specification)
- Apache Derby version 10 database
However, the focus for this article will remain on the creation of these types of Java Persistence Architecture (JPA) entities:
- Generated from pre-existing relational tables (sometimes referred to as a "bottom-up" approach)
- Use database-generated primary key values for the ID attribute
- Are part of a composition (or aggregation) of one or more other JPA entity beans (for example, one-to-one or many-to-one relationships)
Although they are not the focus for this article, the application will use an Enterprise JavaBean (EJB) 3.1 Stateless Session Bean and a servlet that uses the Servlet 2.5 specification.
Before you start
To construct the application, you will need to use these applications:
- IBM Rational Application Developer Version 8.0.2.
Note: After installing Version 8.0, use the IBM Installation Manager to discover and apply fix packs and other maintenance to update your installation to 8.0.2 or later.
- IBM WebSphere Application Server 8.0 beta, March Refresh image (by using the
WebSphere Test Environment that is available with Rational Application
Note: You will need to download and install the March 2011 beta refresh image (see Resources for a link), because you will not be able to use the earlier version of the 8.0 Beta shipped with Rational Application Developer Version 8.0.2.
- Derby database Version 10 provided by Rational Application Developer
Also, extract the resources.zip file (see the Downloads section) to a location of your choice in your file system. It should contain two files:
These resources include a script to create your initial Derby database and an Enterprise Archive (EAR) file that contains artifacts to begin developing your Java Enterprise Edition (JEE) application.
Work with the Acme membership system
Figure 1 represents the physical relational database for Acme's membership subsystem.
Figure 1. The Acme membership data model
To receive Acme Co.'s services and benefits, clients must become members. Clients can choose from Single, Student, or Family memberships (the membership_type field in the membership table identifies the type of membership). Family memberships provide Acme's services to couples and any children that they have who are under the age of 18. To remain members in "good standing," clients must renew their memberships annually.
All memberships will have, at most, one primary member. The primary member is responsible for keeping the membership in good standing and for paying the annual subscription fees.
In addition to having a primary member, a family membership will normally have one or more dependents. There are two types of dependents in a family membership: the spouse and any children younger than 18.
All correspondence between Acme Co. and its members occurs solely through the primary member. Acme collects the address and other contact information for the primary member for all memberships for this purpose.
Set up the WebSphere Application Server
The application you will build in this article will not run using the WebSphere Application Server Version 8.0 Beta that is included in Rational Application Developer Version 8.0. You need to download the WebSphere Application Server Version 8.0 beta March 2011 or later refresh. In addition, the WebSphere 8.0 beta that is included in Rational Application Developer v8.0 cannot be upgraded. This means that you must install the March 2011 v8.0 Beta refresh to a separate location. Fortunately, both versions will co-exist on the same machine.
After downloading and installing the WebSphere Application Server 8.0 beta March 2011 refresh, you need to create a server instance in Rational Application Developer.
- Start Rational Application Developer 8.0.2 using a workspace location of your choice. Start > IBM Software Delivery Platform > IBM Rational Application Developer for WebSphere Software 8.0.2.
- When prompted to enter a workspace location, select the default location provided or enter another convenient location.
- If the Welcome window appears, go ahead and close it.
- If you are not already in the Java EE perspective, open it.
Note: The first time that you switch to this perspective, you could get a dialog window requesting you to enable certain activities or features. Click OK to accept any such requests.
- Within the Java EE perspective, in the Servers view, right-click and select New > Server.
- In the New Server wizard, expand the IBM folder, as shown in Figure 2, select WebSphere Application Server v8.0 Beta, and click Next.
Figure 2. Define a new server to deploy and test your applications
- Name your test environment server
WebSphere Application Server v8.0 Beta March 2011 Refresh, as shown in Figure 3, to avoid confusion with the earlier version of WebSphere Application Server v8 beta included with Rational Application Developer v8. For the Installation directory field, browse to the location where you installed the WebSphere Application Server v8.0 beta March 2011 refresh.
- Click Finish.
Figure 3. Providing the location for the server runtime
Create the Acme membership database
Acme's membership application depends on the existing layout of the Acme database. You will recreate Acme's membership database tables using the embedded Derby database provided by Rational Application Developer.
- Open the Data perspective.
- In the Data Source Explorer view, right-click the Database Connections folder and select New.
- The New Connection wizard will appear. There are three things to change on the
first page of the wizard:
- Select Derby from the list of choices in the Select a Database Manager: panel.
- From the JDBC driver: drop-down list, select Derby 10.2 – Embedded JDBC Driver Default.
- In the Database location: text box, update the default value (in Microsoft Windows, this is typically C:\Documents and Settings\Administrator\MyDB) to C:\Documents and Settings\Administrator\MembersDB.
Figure 4. Creating and connecting to a new Derby database
- Click Finish.
Create the relational tables
Now that you have successfully created the Members database, you will create the relational tables. You will do this by running the members.sql script provided (see Downloads).
- Still within the Data perspective, right-click anywhere in the Data Project Explorer view and select New > Data Design Project.
MembersDBProjectfor the Project name.
- Click Finish.
- Right-click the newly created MembersDBProject project in the Data Project Explorer and select Import.
- In the Import dialog wizard, expand the General folder, select File System and click Next.
- To the right of the "From directory" text box, click the Browse button and navigate to the location where you downloaded and extracted the Members.sql file. Select Members.sql, and click Finish.
- Under the MembersDBProject project folder expand the SQL Scripts folder.
- Right-click Members.sql, and select Run SQL.
- In the Select Connection Profile dialog window, in the Connections list, select MembersDB and click Finish.
If you explore your connection to the Members database through the MemberDB connection, you will notice the creation of new tables in the APP schema.
Use the Identity Value Generation strategy
Having the database generate values for the primary key for a table (and by extension, any foreign key values for related tables) eliminates the burden from the application to do so. That is, not having to generate unique key values for persistent objects within the application allows the focus to remain on core business logic and business rules. This has the positive consequence of enhancing the application's maintainability and readability.
In this scenario, Acme's lead data and application architects want to use the Identity Value Generation approach to remove that burden from the business logic of their various applications. To leverage that capability, JPA can delegate assignment of an entity's ID attribute to the relational database.
The primary key fields in the relational tables for the MembersDB are set to generate unique values to adhere to the identity value generation strategy that Acme developers want to take.
Before you generate the JPA entities, you need to import the beginnings of a JEE 6.0 Enterprise Application project that will have an EJB project and a web project.
Import the membership application into Rational Application Developer
- Switch back to the Java EE perspective.
- Import the initial EAR project that you will build upon:
- From the menu bar select File > Import > Java EE > EAR File, and then click Next.
- Click the Browse button, navigate to the location where
you saved the file AcmeMembershipApplication.ear, and
select it to import.
Important: For Target runtime, make sure that you select the "WebSphere Application Server v8.0 Beta March 2011 Refresh" server that you previously created.
- Click Finish.
Upon successful import, you will have a project layout as shown in Figure 5. There will be three new projects:
- An enterprise application project
- A corresponding web module project
- An EJB module project
You will see errors in the Markers view that you can safely ignore for now.
Figure 5. Acme's enterprise application projects
The EJB project has a stateless session EJB that you will use to invoke your JPA entities to create new members and memberships.
The web project has a simple single servlet that you can easily run in your WebSphere Test Environment to invoke your business logic.
Generate the JPA entities
In this section, you will generate the JPA entities from the Members database tables. These JPA entities provide the foundation of the business logic for Acme's membership system.
First, create a JPA project to host your JPA entity beans:
- Switch to the JPA perspective. Select File > New > JPA Project to bring up the New JPA Project wizard.
- For the Project name, enter
- Make sure that the Add project to an EAR is checked, and then click Next.
- Click Next again on the Java page of the New JPA Project wizard.
- In the JPA Facet page of the wizard, select MembersDB from the Connection drop-down list.
- Click Finish. If you are asked to switch to the JPA perspective, click Yes.
Now that you have a JPA project created, you can generate your JPA entities:
- Right-click the new JPA project that you created, AcmeMembershipApplicationDomain, and select JPA Tools > Generate Entities from Tables.
- On the Select Tables page of the Generate Custom Entities:
- Select MembersDB from the Connection drop-down list.
- Select APP from the Schema drop-down list
- Be sure to check all tables listed in the Tables combination list.
- Check the Update class list in persistence.xml check box.
The Select Tables page of the wizard should look like Figure 6.
Figure 6. Selecting the tables from which to generate JPA entities
- Click Next.
- On the Table Associations page of the Generate Custom Entities wizard, you have an opportunity to generate and shape relationships between the entities that you will generate. Select each of the table associations, and make the necessary edits and selections that give you the same result as shown in Figure 7, Figure 8, Figure 9, and Figure 10.
- Then click Next.
In the screen shown in Figure 7, you are setting the name of the attribute that provides the many-to-one relationship between the dependents in a family and a family membership.
Figure 7. Editing the relationships for Dependent – Membership
Figure 8 shows setting the name of the attribute that provides the aggregate relationship between the primary member and that person's membership with Acme Inc.
Figure 8. Editing the relationship for PrimaryMember – Membership
Figure 9 shows setting the name of the attribute that provides the aggregate relationship between the primary member and that member's residence address.
Figure 9. Editing the relationship for PrimaryMember – Address
Figure 10 shows setting the name of the attribute that provides the aggregate relationship between the primary member and that member's contact information.
Figure 10. Editing the relationship for PrimaryMember - ContactInfo
- On the Customize Default Entity Generation page of the Generate Custom Entities
- Select identity from the Key generator
Note: Here, you are indicating the desire to use the Identity Generation scheme as the approach for generating unique values for primary key attributes for your JPA domain classes.
- Choose Property for the Entity Access radio button.
- Select java.util.Set for the Collections Property Type radio button.
- For the Package field, enter
- Click Next.
- Select identity from the Key generator drop-down list.
- On the Customize Individual Entities page of the Generate Custom Entities
wizard, you can customize numerous characteristics for both the classes and
their underlying attributes.
- Expand Dependent in the Tables and columns list box.
- Under Dependent, select the BIRTHDATE column.
- In the corresponding Mapping type drop-down list, select java.util.Calendar.
- Repeat Step 5 for the BIRTHDATE column in PRIMARYMEMBER and for the LASTRENEWALDATE and MEMBERSINCE columns in the MEMBERSHIP table.
- Click Finish.
Feel free to browse the generated JPA entities in the AcmeMembershipApplicationDomain project.
Adjust the JPA entities
The JPA entities now require some adjustments and enhancement before elaborating on them with further business logic. Adjustments are required to ensure that the entities reflect the business and application domain more accurately.
You will override the database interpretation of the relationship of some of the entities to be one-to-one rather than many-to-one. This will not affect the referential integrity or primary-foreign key relationships between the tables in the membership database. The reason for doing this is to make the application logic reflect the business rules and constraints that exist between the entities more closely.
Adjust Acme's JPA entities to one-to-one, unidirectional relationships
Assume that to reflect the constraints of the business rules for Acme's membership administration, you would like to make a few adjustments to your JPA entities:
- Tighten the cardinality (from many-to-one to one-to-one) for some of the relationships.
- Reduce the navigation flexibility for some of the relationships (from bidirectional to unidirectional).
Both of these changes will make the application more secure and less prone to breaking any of the business rules for Acme's membership application.
Change the cardinality of the relationship
- Open the JPA Primarymember entity.
- In the Java editor, select the address attribute.
- In the JPA Details view, select the many to one hyperlink, as shown in Figure 11.
Figure 11. Changing the cardinality of the relationship
- In the Mapping Type Selection dialog window, select One to One and click OK.
- In the JPA Details view, uncheck the Optional check box and check the All check box for the Cascade options.
- Repeat Steps 1 through 5 for these attributes:
- contactInfo attribute in the PrimaryMember JPA entity
- primarymember attribute in the Membership JPA entity
Step 5 does not change the nature of the relationship of your JPA entities. However, it is a necessary step for making a complex object persistent (for example, an object composed of collections and an aggregation of other complex objects).
Run the Acme membership application
You will now deploy the Acme membership application to the Rational Application Developer WebSphere Test Environment. You will use a servlet to run the Acme membership function to create a new family membership.
- Make sure that you are still in the JPA perspective, and then select the AcmeMembershipApplicationDomain project from the Project Explorer view.
- Right-click and select JPA Tools > Configure Project for JDBC Deployment.
- Figure 12 illustrates the default values for the "Set up connections for deployment" dialog window. Ensure that the defaults are indeed the same as what you see; otherwise, make the necessary changes to match Figure 6.
- Click OK.
Figure 12. The "Set up connections for deployment" dialog view
- Switch from the JPA perspective back to the Java EE perspective.
- In the Servers view, select the WebSphere Application Server v8.0 Beta at localhost, right-click, and select Add and Remove from the context-sensitive menu.
- Select the AcmeMembershipApplication project in the Add and Remove dialog wizard, and click the Add button.
- Click Finish.
- In the Enterprise Explorer view, expand AcmeMembershipApplicationWeb > AcmeMembershipApplicationWeb > Servlets.
- Right-click CreateMembershipServlet, and select Run As > Run on Server.
- If the Run On Server dialog wizard appears:
- Select WebSphere Application Server v8.0 Beta at localhost.
- Check the Always use this server when running this project check box (Figure 13).
- Click Finish.
Figure 13. The Run on Server dialog window
After the WebSphere Test Environment server has started, it will invoke your servlet and open a web page, indicating success in creating a new membership. You can inspect the Derby database tables to confirm addition of the new membership record.
For this article, we used Rational Application Developer tools to rapidly generate and customize JPA entities from a Derby database that had these characteristics:
- Tables that use the Identity Value Generation capability to create unique primary keys values
- A nontrivial set of relationships between the tables
Using the Rational Application Developer environment enabled you to increase your productivity by using views and editors that helped you tailor your JPA entities, thus freeing you from hand coding the required annotations.
Finally, you ran your application by using the WebSphere Application Server conveniently embedded within the Rational Application Developer WebSphere Test Environment.
The author thanks Mike Reid for his thoughtful and thorough review of this article.
|This archive contains two files||resources8996.zip||20KB|
- Read these articles for more helpful information:
- Create bottom-up JPA entities with Rational Application Developer, DB2, and WebSphere Application Server by Ali Manji (developerWorks, 2010)
- Build a Java Data Objects application by using Rational Software Architect 8.0 and the Google App Engine SDK by Ali Manji (developerWorks, 2011)
- Find out more about Rational Application Developer:
- Browse the Rational Application Developer for WebSphere Software page on developerWorks for links to technical articles and many related resources.
- Explore the Information Center.
- Visit the Rational software area on
developerWorks for technical resources and best practices for other Rational
Software Delivery Platform products.
- Stay current with developerWorks technical events and webcasts focused on a variety of IBM products and IT industry topics.
- Attend a free developerWorks Live! briefing to get up-to-speed quickly on IBM products and tools, as well as IT industry trends.
- Watch developerWorks on-demand demos, ranging from product installation and setup demos for beginners to advanced functionality for experienced developers.
- Improve your skills. Check the Rational training and certification catalog, which includes many types of courses on a wide range of topics. You can take some of them anywhere, any time, and many of the "Getting Started" ones are free.
Get products and technologies
- Try Rational Application Developer for WebSphere Software, free.
- Download and install the IBM WebSphere Application Server 8.0 beta March Refresh image (by using the WebSphere Test Environment that is available with Rational Application Developer).
- Evaluate IBM software in the way that suits you best: Download it for a trial, try it online, use it in a cloud environment, or spend a few hours in the SOA Sandbox learning how to implement service-oriented architecture efficiently.
- Check Rational Application Developer wiki to keep up with news and to contribute.
- Join the Development Tools forum to ask questions and participate in discussions.
- Share your knowledge and help others who use Rational software by writing a developerWorks article. You'll get worldwide exposure, RSS syndication, a byline and a bio, and the benefit of professional editing and production on the developerWorks Rational website. Find out what makes a good developerWorks article and how to proceed.
- Follow Rational software on Facebook and Twitter (@ibmrational), and add your comments and requests.
- Ask and answer questions and increase your expertise when you get involved in the Rational forums, cafés, and wikis.
- Connect with others who share your interests by joining the developerWorks community and responding to the developer-driven blogs.