© Copyright International Business Machines Corporation 2002. All rights reserved.
Building J2EE applications that access relational databases can be challenging for experienced developers and is especially so for beginners. Most J2EE applications of any scope require coding JavaTM persistence at some point, even if the application uses Container Managed Persistence (CMP), which delegates a lot of the responsibility for managing the persistence layer to the application server's EJB container. While it is true that CMP simplifies the management and coding of database interactions, it still requires that databases, tables, and schema be created and configured beforehand in order to execute the application that uses CMP. This database set-up stage is typically time consuming and complex, and it usually require database administration expertise as well as privileged access to the database.
A new feature (actually, two new plug-ins) in WebSphere© Studio Application Developer 5.0, known informally as the Table and Data Source Creator, simplifies the set-up of the test backend database and the creation and configuration of test data sources. The Table and Data Source Creator, which operates automatically with a single menu click, is helpful for early testing of an application when it's not important how the database persistence is actually implemented. In the early stages of CMP development and testing, the Table and Data Source Creator handles the persistence issues, and frees you from needing to know how the CMP is persisted -- what database is used, where is it created, how is it maintained, how it is accessed, and so on.
This tutorial will walk you step-by-step through the creation, development, and testing of some simple CMPs, which you will then run in the unit test environment after performing some simple steps to specify and manage the persistence layer with the Table and Data Source Creator. You won't need to know anything specific about the database that persists these EJBs, nor manage it in any way. The database, tables, and the data source that is created to bind to those tables at run time is created automatically, and therefore you can focus on the testing and debugging of the business logic without being distracted by persistence issues.
It is our hope that this novel way of shielding you at the earliest stages of CMP development from worrying about persistence will make developing and testing CMPs no more difficult developing and testing session beans. After you've tested and debugged your CMPs on the unit test server with its managed database and data sources, you may need to deploy and test on the actual database or on a staging server. At that stage you will need to address some of the complex persistence issues. But in your initial testing and debugging of CMP code, the largely automated test environment of WebSphere Studio can handle all of the details for you, freeing you to just develop, run, and test.
What you will accomplish in this tutorial
This tutorial shows you how to develop and test two simple CMPs --
Employee and
Department. They are fully persisted in a
relational database -- Cloudscape 5.0 (also known as DB2j), a Java-based,
lightweight, embedded database system that is supported in WebSphere 5.0
for testing and samples. The tutorial includes the following development
and testing tasks:
- Creating an EJB 2.0 project
- Creating two EJB 2.0 CMP EJBs
- Performing a top-down EJB-to-Relational-Database-Management (RDB) mapping
- Generating deploy and RMIC code for WebSphere Application Server 5.0
- Specifying a JNDI name for the EJB module and for individual EJBs
- Setting the current backend ID to the backend that you created during the top-down mapping
- Creating a WebSphere 5.0 Test Environment (Beta) server instance
- Auto-creating the database, tables, and data source
- Starting the server and bringing up the Universal Test Client (UTC)
- Running and testing both EJBs with the UTC, using real database persistence
- (As an alternative) Importing the supplied EAR module instead of developing from scratch
Please follow the instructions below carefully, because each step must be
successfully completed in order to create the finished example. The two
EJB 2.0 CMPs that you will create -- Employee
and Department -- must be contained in an EJB
2.0 project, because the Table and Data Source Creator uses features
available only in EJB 2.0. The project name can be anything you want --
this article uses MyCompany. You are also free
to use values other than the ones used below. So if you are ready, fire up
your copy of WebSphere Studio Application Developer 5.0 EA and let's
go!
- Create a new EJB 2.0 Project by selecting File => New
=> Project => EJB => EJB Project.
Figure 1. Creating an EJB 2.0 project.
- Name the EJB project
MyCompanyand accept the default name,DefaultEAR, for the enterprise application project (the EAR module). Accept the rest of the defaults and click Finish.
Figure 2. Supplying the EJB and EAR module project names.
2. Create the EJB 2.0 CMPs Employee and Department
- From the J2EE perspective, create two new CMPs --
EmployeeandDepartment: Select File => New => Enterprise Bean and from the list box, select the MyCompany project. - Specify the values in Figure 3, enabling the CMP 2.0 radio button and
giving a bean name of first
EmployeeandDepartmentthe second time through. Click Next.
Figure 3. Creating the CMPs.
This tutorial shows you how to create a CMP 2.0 bean and attributes because it is the more recent EJB level. But the Table and Data Source Creator handles CMP 1.1 beans as well, and if you wanted to, you could create them, though the wizard pages are slightly different. - For CMP 2.0 beans, the EJB specification states that the default
interface is the local interface ("Local client view"), introduced
with CMP 2.0, which helps to reduce the network traffic and other
overhead from calls between EJBs in the same container. Before local
interfaces, the only choice was remote interfaces, increasing this
overhead even when the calls were between beans in a single container.
Accept the defaults and click Add in the CMP attributes
section.
Figure 4. Local client view.
- Create the CMP attributes as follows:
Employee Field 1: firstName, String, Field 2: lastName, String Field 3: empNum, int (key) Department Field 1: deptName, String Field 2: deptNum, int (key)
- Enter these fields in the Create CMP Attribute dialog. Check the
Promote getter and setter methods to local interface check
box, which adds the signatures to the interface for you, exposing
those methods. Check the Key field check box for the key field
for each of the two CMPs.
Figure 5. Specifying the CMP attributes.
3. Generate an EJB to RDB mapping for Cloudscape
- Select the MyCompany EJB project, then right-click and select
Generate => EJB to RDB Mapping.
Figure 6. Generating a mapping.
- Specify a new top-down mapping (a mapping where you want to create
database tables that don't exist from CMPs that do exist). The
language the wizard uses is Create a new backend folder. Make
sure the radio button has Top Down selected (should be the
default).
Figure 7. Selecting Top Down
- Select Cloudscape V5.0 for the backend target database. You can
supply any name for the Database and Schema names, but I've specified
CompanyDB. You must specify a database name to proceed through the wizard, but the schema name can be blank or justNULLID(the default), which means no schema name or table qualifier will be created. You don't need to generate the DDL, but I recommend doing so because it is sometimes useful for debugging.
Figure 8. Using Cloudscape as the target database.
- The completed and mapped EJB structure from the J2EE view should now
look like this:
Figure 9. Completed EJB module view.
- Optionally, view the Enterprise Beans (EJB view) and Tables (RDB view)
representation of the mapping to make sure it looks right. It should
look like this:
Figure 10. Mapping representation.
4. Generate Deploy and RMIC Code
- Select the MyCompany EJB project, then right-click and select
Generate => Deploy and RMIC Code.
Figure 11. Generating deploy and RMIC code.
- Select both the Employee and Department beans that you
should have created for deployment. If they aren't selected, click
Select all => Finish.
Figure 12. Generating deploy code for Employee and Department beans.
5. Specify the JNDI name to be used for lookup.
A JNDI name is a logical reference to a resource registered in JNDI that your application will use at run time. The data source that will be created automatically for you in a subsequent step will need a JNDI name by which it may be referenced to connect to the database. So the JNDI name is the name that the naming service associates with the data source instance used to interact with the backend.
You may supply either a default JNDI name that will be used for all EJBs in a given application module (EAR), a bean-specific name that overrides the default name for that bean, or a mixture of both using the Deployment Descriptor Editor. If you don't supply a JNDI name, no data sources can be generated, since it is impossible to know beforehand what name should be bound to the data source. During table and data source creation a warning will prompt you to specify a name and try again.
- 1. The typical J2EE use for CMP 2.0 is to specify a single default JNDI name, and in WebSphere Studio you do this on the first tabbed page, the Overview tab of the Deployment Descriptor Editor. Enter either a "default" JNDI name or an EJB-specific name at the individual EJB Level.
- To set a default name, set the default CMP Factory Connection
Binding JNDI name to your designated value in the first
Overview tab page of the Deployment Descriptor Editor for
the entire EJB module.
Figure 13. Setting a default level binding.
- As mentioned above, if there is a requirement for an individual bean
or beans to override the default, set this in the CMP Container
Factory JNDI Namefield on the Beans tab for the
particular bean. Below is an illustration of supplying a JNDI name for
the Employee bean:
Figure 14. Setting the JNDI name at the EJB level.
6. Set the Current Backend ID to Cloudscape.
If you already have backend IDs created for the EJB project (which you would typically not have in our case if you are following the instructions), set the currentone you want to use at run time. This is because the current one remains the old current one until you explicitly change it. This is important at run time because the server needs to know which backend to use (if there are multiple backends), since WebSphere 5.0 supports multiple backends at run time, but only loads a specific set of these persisters as specified here. You can set this value on the Overview page of the Deployment Descriptor Editor.
Figure 15. Setting the current backend.
7. Create a new WebSphere 5.0 Test Environment (Beta) server
- Create a new server project and a WebSphere 5.0 (Beta) unit test
server and configuration. You can specify any names you want.
Figure 16. Creating the server resources.
- Add the MyCompany project (module) to the sever configuration that you created.
8. Create tables and data sources
Here is where you (finally) get a chance to use the new Table and Data Source Creator, which should make your life a bit easier.
- From the Servers view, select the server you created, right-click, and
select Create tables and data sources.
Figure 17. Auto-creating your tables and data source.
- Make sure the project contains Cloudscape-mapped CMPs, and that you
performed the mapping as instructed above. If you try to run the Table
and Data Source Creator on an EJB project that either doesn't contain
CMPs or doesn't contain a top-down map for Cloudscape, you won't be
able to continue this action. You will instead receive then
informational message below. It is a hint that you need to make sure
the project qualifies by ensuring the map has been created as
expected.
Figure 18. Action could not be performed.
- If you've followed the instructions properly up till now, both the
database tables and data source will have been generated for you. The
informational message at the end of the process will confirm this
status as well as show the individual status of the various SQL calls
made to the database during these various tasks. If the export task
was successful, the item will have
[Successful]appended to it. If it fails, it will say[FAIL], with a description of the failure.
Figure 19. Status messages.
- As mentioned above, database tables will always be created even
if no JNDI name was specified in the EJB deployment descriptor, but
data sources will not be created. If that is the case, a
different informational message will suggest that you supply a single
name per EJB module at minimum and try again.
Figure 20. Need to set at least one JNDI name.
- If you receive the warning message in Figure 20 above, or if you
already created a data source bound to a specific JNDI name in the EJB
module, those data sources will not be created or re-created, since
there is no need to do so. The status message displayed at the end of
the process will inform you of that. However, if you manually delete
the data source in the server creation, then in that case it will be
re-created. Only one copy of a unique JNDI name is permitted on any
particular server, to make it possible to uniquely look up these data
sources on the naming service for this server instance.
Each time you rerun the Create tables and data source action, the database tables are re-created after performing a drop database action. If there is data you'd like to keep around in a particular database, it's easy to just copy the database directory to some other location, so that it will not be dropped and overwritten. The tables generated for testing are considered to be a form of generated ("test") code, and so rerunning the action will regenerate that code, which should hopefully cater to the typical usage.
Figure 21. Data sources not created or recreated under certain conditions.
- So then, if a JNDI name was specified and the data source for a given
JNDI does not already exist for this server instance, a data source
for Cloudscape will automatically be created. In the illustration
below, a bean-specific data source name for the Employee bean has been
supplied. Though you typically don't need to, you can view the data
source from the data source tab of the server configuration
editor.
Figure 22. Server configuration page for data sources.
- Although a data source will automatically be created for you, you are
of course free to "tweak" it if you feel so inclined. The settings
that are created automatically are set for the typical, default case.
Use the server configuration data source page to modify the values.
Figure 23. Viewing or modifying the settings for the generated data source.
- If you want to use another tool, such as CloudView, to view or
manipulate the database and the tables created or the current records
(EJBs) persisted there, you should know that the database and tables
will be created in the file system under the server's temporary
directory under the workspace. The path to the database (a directory
that is named the same as the database name entered during the top
down mapping) would be:
<WORKSPACE_DIRECTORY>\.plugins\com.ibm.etools.server.core\tmpNN\databases
Figure 24. Actual location of the database tables.
9. Start the server and browse to Universal Test Client (UTC)
- Start the server and observe the console message that the data source
bindings are set properly and the EJB application is successfully
started. Exceptions or errors at these points suggest that you may
have introduced an error in your configuration.
... [10/6/02 16:53:21:005 EDT] 2f5d0698 ResourceMgrIm I WSVR0049I: Binding CMP unit test environment data source as CompanyDataSource [10/6/02 16:53:21:305 EDT] 2f5d0698 ResourceMgrIm I WSVR0049I: Binding CMP unit test environment data source_CF as eis/CompanyDataSource_CMP ... [10/6/02 16:53:31:069 EDT] 2f5d0698 ApplicationMg A WSVR0200I: Starting application: DefaultEAR [10/6/02 16:53:31:089 EDT] 2f5d0698 EJBContainerI I WSVR0207I: Preparing to start EJB jar: MyCompany.jar [10/6/02 16:53:32:031 EDT] 2f5d0698 EJBContainerI I WSVR0037I: Starting EJB jar: MyCompany.jar [10/6/02 16:53:34:815 EDT] 2f5d0698 ApplicationMg A WSVR0221I: Application started: DefaultEAR ...
- From the home page of the UTC, click JNDI Explorer to browse to
the JNDI Explorer. Expand the Local EJB Beans node (recall, you
were only instructed to use local client view) and drill all the way
down. You should see the
EmployeeandDepartmentEJBs registered in the JNDI namespace
Figure 25. Local EJB beans home interfaces.
- Depending on which bean you choose to test, click on either the
Employee and Department home, and create instances
of that CMP. You can always browse back a page and load the other bean
as well, which is what I've done below:
Figure 26. Ready to use EJB references.
10. Test the CMP methods with real database persistence
The execution of the setter methods for the CMP attributes should result in a new record (EJB) being added to the database transparently without you needing to know how or where it is happening. This is the testing environment we have provided for you in a largely transparent fashion, where you can just treat your CMP as a plain session bean in terms of the difficulty of testing it.
- Select one of the setter methods and supply an appropriate value.
Below I am calling the
setDeptName()method of the Department bean passing a department nameDevelopment:
Figure 27. Invoking a CMP setter persistence method.
- Select the matching getter method and execute it. The execution of the
getter methods for the CMP attributes should result in the new record
added (the EJB) being accessed from the database. Invoking both the
the setter and matching getter, and getting expected values shows that
the bean is working as designed.
Figure 28. Invoking a CMP getter persistence method.
11. Import the supplied EAR module.
Some people may find it easier to work from the supplied source rather than perform all the steps in this tutorial You can easily import the EAR module and get the CMPs up and running with a few simple steps:
- Download the NewbieCMP file and extract CompanyEAR.ear to a convenient location.
- Select File => Import => EAR Module to bring up the Enterprise Application Import wizard.
- Specify the path to the EAR file and a project name of your choosing,
such as
DefaultEAR.
Figure 29. Importing an EAR module with ready to use code.
- Accept all the other defaults and click Finish.
- Import the server configuration (available in the download) by
selecting File => Import => Server Configuration.
Then, for example, enter the following values:
Configuration Name: MyTestServer Folder: Server Projects Configuration Type: WebSphere 5.0 Server Configuration (Beta) Location: Directory to which you unzipped server configuration to
When prompted, if you want to create a new server project with the nameServer Projects, click Yes.
Figure 30. Importing the ready-made server configuration.
- Select the Server Projects project, right-click, and select
New => Server and create a server called
MyTestServer, using the same name as the server configuration (or a different name if you want). Follow the same instructions for Step 7 above. - Switch the server configuration from No Configuration to
MyTestServer:
Figure 31. Switching server configurations to the one imported.
- Starting at development step 8, create the tables and data source and proceed through the rest of the steps. Run and test the CMPs.
This tutorial has demonstrated the new Table and Data Source Creator in WebSphere Studio Application Developer 5.0. It helps streamline CMP development by freeing you from bothering with database management and configuring servers in the early stages of development. In this way, you can run and test CMPs "out of the box" quickly and easily without an external database system, as easily as you can do with session beans in previous versions of Application Developer. This helps you get your CMPs running quickly, so that you can spot the errors in their business logic connected with this layer. In the early stages of development, it pays off to give more emphasis to application logic and less to how the beans are are eventually deployed and persisted on the target systems.
Question: You mention Cloudview in your tutorial. Is there a way to
start Cloudview from inside WSAD? When I start it from outside using
db2j.jar,
db2jtools.jar, and
db2cview.jar, I still get a "class not found"
exception when I try to open the databases.
Response from author: Cloudscape tools cannot be launched from within WSAD V5 because they are not supported. I believe they are not supported by WAS either, although they are included with the WAS run time for the benefit of customers who want to use them. That being said, it is relatively easy to launch Cloudview from the command line and work with the databases created by the Table Creator or with other tables. Again, the reason I did not mention this in my article is that it is unsupported. With the proviso that Cloudview is unsupported and undocumented, here are the instructions for using it:
- The Cloudscape jar run time,
db2j.jaris found in the base WAS run time inWSAD_ROOT\runtimes\base_v5\lib\db2j.jar. - The Cloudview run time is in
WSAD_ROOT\runtimes\base_v5\lib\db2jcview.jar. - The other Cloudview tools are in
WSAD_ROOT\runtimes\base_v5\lib\db2jtools.jar. - Set the
WAS_HOMEenvironment variable to WSAD 5 WAS_HOME, which isWSAD_ROOT\runtimes\base_v5. - Set the
JAVA_HOMEenvironment variable to any JVM you want to use, including the IBM JDK/JRE atWSAD_ROOT\runtimes\base_v5\java. - To launch Cloudview, enter this command:
"%JAVA_HOME%/bin/java" -ms32M -mx32M -classpath "%WAS_HOME% \lib\db2j.jar;%WAS_HOME%\lib\ db2jtools.jar;%WAS_HOME%\lib\db2jcview.jar;%WAS_HOME%\lib\ jh.jar" com.ibm.db2j.tools.cview
Rereading your comments again, I see that you are launching Cloudview okay from the command line, and that is not the problem. Here is what may be happening: If you are trying to open databases that are in use by the app server, and the Cloudscape database, running by design in embedded mode, is not accessible, then you will get exceptions. If you use the Table Creator to create tables and datasources and then run the app server, the databases will be in use by the app server. When the datasources are bound to the database, it becomes unusable by other tools and even other instances of the app server. Therefore the table and datasource creator action is disabled when the server is running. To use Cloudview in this situation, stop the app server and then use the tools to access the database. If you still get errors, you are not launching Cloudview properly. I personally use Cloudview to look at the tables created by the table creator when the app server is not running.
To see additional user comments, click the View results button above.
| Name | Size | Download method |
|---|---|---|
| NewbieCMP.zip | 100KB | FTP |
Information about download methods

Sheldon Wosnick is an Advisory Software Engineer on the WebSphere Studio Application Developer Server Tools team at the IBM Toronto Lab. With his teammates, he is responsible for the entire server run time and unit test environment for the WebSphere Studio family of products. Previously, he was a member of the VisualAge© for Java WebSphere Tools team. Sometimes fondly known as the "run time guy," he designed and integrated the WebSphere Test Environment and the Apache Tomcat Test Environment, two very popular features in VisualAge for Java. He also designed and implemented the Table and Data Source Creator plugins demonstrated in this tutorial. You can reach Sheldon at swosnick@ca.ibm.com.
Comments (Undergoing maintenance)





