Testing Container Managed Persistence EJBs with the Table and Data Source Creator in WebSphere Studio Application Developer 5.0

Building J2EE applications that access relational databases and require Java persistence coding can be challenging. A new feature of WebSphere Studio Application Developer 5.0 -- the Table and Data Source Creator -- simplifies the creation and configuration of test data sources, thus freeing you from dealing with persistence isssues in the early stages of development so that you can focus on the testing and debugging of the business logic.


Sheldon Wosnick, Software Developer, IBM Toronto Lab

Photo of Sheldon WosnickSheldon 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.

16 October 2002

© 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:

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!

1. Create an EJB 2.0 project

  1. Create a new EJB 2.0 Project by selecting File => New => Project => EJB => EJB Project.
    Figure 1. Creating an EJB 2.0 project.
  2. Name the EJB project MyCompany and 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

  1. From the J2EE perspective, create two new CMPs -- Employee and Department: Select File => New => Enterprise Bean and from the list box, select the MyCompany project.
  2. Specify the values in Figure 3, enabling the CMP 2.0 radio button and giving a bean name of first Employee and Department the 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.
  3. 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.
  4. Create the CMP attributes as follows:
    Field 1:     firstName, String, 
    Field 2:     lastName, String 
    Field 3:     empNum, int (key) 
    Field 1:     deptName, String 
    Field 2:     deptNum, int (key)
  5. 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

  1. Select the MyCompany EJB project, then right-click and select Generate => EJB to RDB Mapping.
    Figure 6. Generating a mapping.
  2. 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
  3. 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 just NULLID (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.
  4. The completed and mapped EJB structure from the J2EE view should now look like this:
    Figure 9. Completed EJB module view.
  5. 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

  1. Select the MyCompany EJB project, then right-click and select Generate => Deploy and RMIC Code.
    Figure 11. Generating deploy and RMIC code.
  2. 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. 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.
  2. 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.
  3. 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

  1. 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.
  2. 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
    Data sources already created
  6. 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.
  7. 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.
  8. 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:
    Figure 24. Actual location of the database tables.

9. Start the server and browse to Universal Test Client (UTC)

  1. 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 
    [10/6/02 16:53:21:305 EDT] 2f5d0698 ResourceMgrIm I WSVR0049I: 
    Binding CMP unit test environment data source_CF as 
    [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 
  2. 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 Employeeand Department EJBs registered in the JNDI namespace
    Figure 25. Local EJB beans home interfaces.
  3. 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.
    Using local 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.

  1. 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 name Development:
    Figure 27. Invoking a CMP setter persistence method.
  2. 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:

  1. Download the NewbieCMP file and extract CompanyEAR.ear to a convenient location.
  2. Select File => Import => EAR Module to bring up the Enterprise Application Import wizard.
  3. 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.
  4. Accept all the other defaults and click Finish.
  5. 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 name Server Projects, click Yes.
    Figure 30. Importing the ready-made server configuration.
  6. 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.
  7. Switch the server configuration from No Configuration to MyTestServer:
    Figure 31. Switching server configurations to the one imported.
  8. 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.

Questions from users

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:

  1. The Cloudscape jar run time, db2j.jar is found in the base WAS run time in WSAD_ROOT\runtimes\base_v5\lib\db2j.jar.
  2. The Cloudview run time is in WSAD_ROOT\runtimes\base_v5\lib\db2jcview.jar.
  3. The other Cloudview tools are in WSAD_ROOT\runtimes\base_v5\lib\db2jtools.jar.
  4. Set the WAS_HOME environment variable to WSAD 5 WAS_HOME, which is WSAD_ROOT\runtimes\base_v5.
  5. Set the JAVA_HOME environment variable to any JVM you want to use, including the IBM JDK/JRE at WSAD_ROOT\runtimes\base_v5\java.
  6. To launch Cloudview, enter this command:
    "%JAVA_HOME%/bin/java" -ms32M -mx32M -classpath "%WAS_HOME%
    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.


Code sampleNewbieCMP.zip  ( HTTP | FTP )100KB


developerWorks: Sign in

Required fields are indicated with an asterisk (*).

Need an IBM ID?
Forgot your IBM ID?

Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.


All information submitted is secure.

Dig deeper into WebSphere on developerWorks

ArticleTitle= Testing Container Managed Persistence EJBs with the Table and Data Source Creator in WebSphere Studio Application Developer 5.0