11602.1R1 EJB 2When we select the Bean tab, we activate BeansExpress™ which is an interface for...
Transcript of 11602.1R1 EJB 2When we select the Bean tab, we activate BeansExpress™ which is an interface for...
Getting StartedGuide – part IICreating your Second EnterpriseJavaBean
Container Managed Persistent Bean
by Gerard van der Pol and Michael Faisst, Borland®
Preface
Introduction
This document provides an overview of the development
process of Enterprise JavaBeans™ (EJB™) with Borland
JBuilder™ 4 Enterprise and Inprise™ Application Server™
4.1 (IAS4.1).
In ten steps we will develop an Enterprise JavaBean,
deploy it to the Inprise Application Server, and create a
client application that will use the developed bean. We
will also see how to use the remote debugging facilities
of JBuilder and IAS.
This document is not a reference on Enterprise
JavaBeans; instead, it is designed to get you started
quickly using both products.
Definitions
Acronym Description
CORBA Common Object Request Broker
Architecture
EJB™ Enterprise Java Beans™
IAS Inprise™ Application Server™
RMI Remote Method Invocation
JPDA Java Platform Debugger Architecture
JBuilder
Table of Contents
Preface 1
Developing an Enterprise JavaBean in tensteps 2
The EJB™ Entity Bean modeler 12
Congratulations! 15
™
JBuilder™
2
Additional information
Inprise Application Server (now Borland® AppServer™)
http://www.borland.com/appserver/
Borland JBuilder
http://www.borland.com/jbuilder/
Borland AppCenter
http://www.borland.com/appcenter/
Borland Enterprise JavaBeans Programmers Guide
http://www.borland.com/techpubs/appserver/
Enterprise JavaBeans with Paper
http://www.borland.com/visibroker/ , click on White Papers
Sun’s Java® 2 Platform Enterprise Edition
http://java.sun.com/j2ee/
Sun’s Enterprise JavaBeans
http://java.sun.com/products/ejb/
Configuring JBuilder™ for EnterpriseJavaBean developmentIn order to be able to easily develop an Enterprise
JavaBean using JBuilder we will have to configure
JBuilder for both CORBA and Borland Application Server
integration. Read the white paper “Getting Started Guide -
part I, Creating your first Enterprise JavaBean, Stateless
Session Bean” by Gerard van der Pol and Michal Faisst
for details on how to do this.
Developing an Enterprise JavaBean inten stepsJBuilder provides several wizards to assist in creating
Enterprise JavaBeans and the required interfaces. This
document describes an example of creating an Enterprise
JavaBean, in this case an Entity Bean. The bean we create
will represent a very simple product that consists of a
name and a price. The goal of this example is to
demonstrate the development process of an Entity Bean
using Container Managed Persistence.
Step 1. Create a new Project
We first create a new project or open an existing project.
To create a new project,
♦ Select File|New Project from the JBuilder menu.
♦ Enter the project name ProductEntityBean.
In the next screen we can set the name of the project file
(*.jpx), the target JDK™, and the required libraries. We set
the target JDK to 1.3.0 and in the list of required libraries
we add the VisiBroker® 4 library and the “Inprise
Application Server 4.1” library. (If vbjorb.jar and
vbjdev.jar are already in the “Inprise Application Server
4.1” library the VisiBroker Library is not needed.)
JBuilder™
3
In the third screen of the wizard enter the Title, Author,
Company, and Description fields. This is not required.
Click Finish.
Step 2. Create the EJB group
In JBuilder 4 a new concept is introduced, the EJB group.
An EJB group is a logical grouping of Enterprise
JavaBeans that is intended to be deployed in a single .jar
file. In other words, this EJB group is the first step to the
final deployment jar.
We create an EJB group by going to the object gallery
( F ile - N ew) and selecting the “Empty EJB Group”
wizard.
This will start the EJB group wizard. This wizard will ask
us a name for our EJB group. This is going to be the
name of the .jar file in which we will deploy our beans.
We will call the EJB group “Product”.
Click OK to create the EJB group. With every Enterprise
JavaBean we will start to develop, JBuilder will ask us
which EJB group to place it in. If there is already an EJB
group available in our project, this group will be available
for selection from a drop down list. But we can also
create multiple EJB groups within a single project.
Step 3. Create the Enterprise JavaBean
In step 3 we are going to create the Enterprise JavaBean.
There are two ways of creating this Entity Bean. The first
way we will discuss is creating an entity from scratch.
Later in this document we will discuss how to create an
Entity bean based on an existing database table. The
second way will be much simpler and faster. However,
we are first going to see how to do this the standard way.
We do that for two reasons:
The first reason is to become aware of the steps to take
when developing an Entity Bean. That will make it easier
to understand the generated code.
The second reason is that we will not always have an
implemented data model available.
Building from scratch
Select File|New, then select Enterprise JavaBean from
the Enterprise tab of the Object Gallery.
JBuilder™
4
In the first dialog of this wizard we are asked which EJB
group we want to use. We will go for the EJB Group we
have created in Step 2 and click on N ext >.
This will bring up the second page of the EJB wizard. In
this page we enter information about the bean we are
going to create. By default the default values of the
properties of the bean are prompted. We will go with the
suggested package name, but enter a different name for
the classname. We will call the bean ProductBean and
set the bean type to “ C ontainer managed persistence
entity bean” with the “p r imary key class” to
java.lang.String.
In the next page we can set the name of the home and
remote interface and the JNDI name for our bean. The
default names are generated based on the package name
and the Bean name which we have already entered. We
will go with the suggested values and click on F inish.
A new bean called ProductBean.java is created. JBuilder
generates the following source code for Enterprise
JavaBean based on the information supplied to the
wizard.
package productentitybean;
import java.rmi.*;
import javax.ejb.*;
public class ProductBean implements EntityBean {
EntityContext entityContext;
public String ejbCreate() throws CreateException {
/**@todo: Implement this method*/
return null;
}
public void ejbPostCreate() throws CreateException {
}
public void ejbRemove() throws RemoveException {
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbLoad() {
Note. The naming convention is beanname for the remote interface,
beannameBean for the implementation and “beannameHome” for
the home interface.
JBuilder™
5
}
public void ejbStore() {
}
public void setEntityContext(EntityContext entityContext)
{
this.entityContext = entityContext;
}
public void unsetEntityContext() {
entityContext = null;
}
}
Notice that in the source code we see this comment line:
/**@todo: Implement this method*/
This is a special type of comment, it will be seen by the
IDE as To-Do item and will appear in the structure pane
in the lower left corner. Double-click on the To-Do-item to
jump to the corresponding position in the code.
Step 4. Adding the properties to the
Enterprise JavaBean
Next, we will ‘code’ the bean by adding public method
signatures for getting and setting the values of the data
members. After that we will alter the ejbCreate method
which is called to create an instance of the bean (Actually
the ejbCreate method will perform an insert in the
database). But first we add the public methods for
adjusting the values of the data members, for this we use
BeansExpress™.
If we look at the bottom of the source code (in the
content pane) we see that there is a source tab, a
designer tab, the Bean tab, and the doc tab.
For background information on these tabs read the
Getting Started Guide that comes with JBuilder.
When we select the Bean tab, we activate BeansExpress™
which is an interface for creating JavaBeans. If the current
java class is an Enterprise JavaBean it will show another
interface based on extending an Enterprise JavaBean. We
are going to use this wizard to extend our bean (Adding
data members, getter, and setter methods to both the
bean and the remote interface). In BeansExpress there is
a second row of tabs available. Select the properties tab;
the form should look something like this.
Click on the Add property... button. This activates a
frame for generating code to create a property, as well as
a getter and setter method for this property. The first
property we add, we will call “name”, it is of the type
String (or “java.lang.String”), and only has a getter
method. This is later going to be the primary key of the
Bean, so, once created, the value must remain the same.
Click the Apply button.
We add another property which we will call “price”, set
the type to Float (or java.lang.Float), make sure the
getter and setter checkbox are both checked, and click on
OK.
JBuilder™
6
Next, we switch to the methods tab and see our three
new methods at the bottom of the methods list. At the left
of our method names there is a checkbox. Select these
checkboxes to update the remote interface.
If we switch back to the source tab, we see that
BeansExpress has added sourcecode to the sourcefile.
This code should be something like this:
package productentitybean;
import java.rmi.*;
import javax.ejb.*;
public class ProductBean implements EntityBean {
EntityContext entityContext;
public String name;
public Float price;
public String ejbCreate() throws CreateException
{
/**@todo: Implement this method*/
return null;
}
...
public String getName() {
return name;
}
public void setPrice(Float newPrice) {
price = newPrice;
}
public Float getPrice() {
return price;
}
}
BeansExpress has created two public data members.
The only thing left to do is add the code for the
ejbCreate method. As stated, ejbCreate will perform an
insert into the database. Therefore the least we have to
do is provide the constructor with information needed for
this insertion, being the values to insert into the database.
We change the ejbCreate method into the following:
public String ejbCreate( String newName,
Float newPrice) throws CreateException {
this.name = newName;
this.price = newPrice;
return null;
}
We should also add the parameters of the ejbCreate to
the ejbPostCreate method, resulting in:
public void ejbPostCreate(String newName,
Float newPrice) throws CreateException {
}
Al this should result in the following code for:
package productentitybean;
import java.rmi.*;
import javax.ejb.*;
public class ProductBean implements EntityBean {
EntityContext entityContext;
public String name;
public Float price;
public String ejbCreate(String newName,
Float newPrice) throws CreateException {
this.name = newName;
this.price = newPrice;
return null;
}
public void ejbPostCreate(String newName,
Float newPrice) throws CreateException {
}
public void ejbRemove() throws RemoveException {
}
JBuilder™
7
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbLoad() {
}
public void ejbStore() {
}
public void setEntityContext(EntityContext context) {
entityContext = context;
}
public void unsetEntityContext() {
entityContext = null;
}
public String getName() {
return name;
}
public void setPrice(Float newPrice) {
price = newPrice;
}
public Float getPrice() {
return price;
}
}
Step 5. Compiling and generating the stubs
and skeletons
The next step is to compile and generate the IIOP stubs
and skeletons. These stubs and skeletons are used to
enable the Enterprise JavaBeans to be contacted by RMI
over IIOP (see the Java 2 Enterprise Edition Platform
specification on RMI over IIOP).
♦ Select the ProductHome.java file in the project pane
(upper left pane).
Right-click to produce the popup-menu and choose the
“Properties...” menu.
♦ Select the Build tab
♦ Select the VisiBroker tab within the Build-tab and
enable “Generate IIOP” checkbox and Click OK
Later, when we select Project|Make Project, this will
start the generation of the IIOP classes based on the
Home and Remote interfaces followed by a compilation
of the Java code.
Step 6. Updating the Deployment Descriptor
By means of the Deployment Description Editor™ plug-in
we will edit the deployment descriptor. The deployment
descriptor can be looked at by double-clicking the EJB
Group, “Product.ejbgrp” which can be found in the
project pane. The Deployment Descriptor Editor (DDE)
can be used to finish creating the necessary xml
deployment description files. The DDE will add the
settings that are defined in the EJB 1.1 specifications to
JBuilder™
8
the ejb-jar.xml file and create an inprise-ejb.xml file
containing additional settings needed for deployment, but
not defined in the EJB 1.1 specification. These files,
however, are not shown in the project pane.
Basically, the structure pane at the lower left corner
shows three nodes: a bean node (if there are more
Enterprise JavaBeans in the current EJB group, we will
have a bean node per Enterprise JavaBean), a “Security
Roles” node, and a “Data Sources” node.
If we select our bean in the structure pane, the
Deployment Description Editor shows the following tabs
which relate to the bean:
- Main (General bean info)
- Environment (general environment settings)
- EJB References (Reference to other Enterprise
JavaBeans like master detail relations)
- Security Role References (linking global
security roles to bean specific security roles)
- Resource References (linking Entity bean to a
datasource)
- Persistence (linking a bean to a table and
define data member to field mappings)
- Finders (defining Queries for declared finder
methods)
- Properties (Setting bean specific properties)
Select the main tab of the editor as shown in the picture
above. Notice that a lot of information is already set by
earlier actions. The first thing we have to do is set a
datasource. To do this, we right click the Data Sources
and select “New Data Source”. We give this Data Source
the name “DataSource/Product” and select OK.
Open the Data Sources node and select the data source
we have just created. Set the following properties for this
data source:
♦ URL: jdbc:borland:dslocal:ejbcontainer
♦ Username : scott
♦ Password : tiger
♦ Driver Class name :
com.borland.datastore.jdbc.DataStoreDriver
In this example, we use a local connection to a
JDataStoreTM database, but you can also use a remote
connection to other databases.
JBuilder™
9
Now that we have defined the data source we are going
to use, we will have to set the deployment descriptor for
our bean to use this data source. Select the product bean
in the structure pane (the lower left pane) and switch to
the “Resource Reference” tab. Click the Add button to
create a new Resource Reference. We call the resource
“dsProduct” and set the type to “javax.sql.DataSource”.
Authentication is going to be done by the container. Refer
the resource to the new datasource we have created by
its JNDI name “DataSource/Product” and make sure the
CMP (Container Managed Persistence) is checked.
Next we switch to the persistence tab. In this tab we map
the bean to a database table.
We enter the table name and the field names and check
the Primary key checkbox for the field that is the primary
key of our table. The frame should look something like
this:
To complete our Enterprise JavaBean we need to add a
container transaction to the assembly descriptor. Open
the Container transaction node of our bean in the
structure pane. Click On the add button to create a new
transaction policy.
A new container transaction is created.
It is possible to set the transaction attribute per Bean, per
Interface, or per method, possible values are:
- Not supported;
- Supports;
- Required;
- RequiresNew;
- Mandatory;
- Never.
For this bean we select the whole bean (interface = *;
Method = *) and set the transaction attribute to
“Required”, as this is an entity bean that is stored in a
database and therefor uses transactions. It is possible to
make a group of transaction policies for the various
interfaces/methods in different combinations.
JBuilder™
10
Before we go to the next step, we can verify if the
deployment descriptor is correct. Click on the verify
button on the top of the page.
The message log window appears and the verification
process starts.
Once the deployment descriptor has been verified we can
build the project. (Select the Project menu and click on
“Rebuild project ProductEntityBean.jpx” or right-click the
“ProductEntityBean.jpx”-node in the project pane and
select “Rebuild” or click on the rebuild button as shown
in the picture below.
By rebuilding the project we actually first generate all the
desired IIOP classes from the home-interface, compile all
the Java code that is not in a stable package, and then
create a deployment jar based on our Enterprise
JavaBean. We can find this jar-file by looking in the
“Product.ejbgrp” node.
Step 7. Deploying the bean to the Inprise
Application Server
In order to have the bean available in our Application
Server environment, we will have to deploy it to a
container.
To do so, we can use the EJB Deployment Wizard from
the tools menu. This wizard makes it possible to deploy
our bean(s) from within JBuilder. In order to successfully
deploy our beans, we need to have an application server
running.
Select T ools, E JB Deployment… to activate the wizard.
The wizard is the same wizard as the Deployment wizard
that is activated from within the Inprise Application
Server Console.
In order to deploy your bean, do the following:
We will use the Quick deployment for normal single jar
deployment. So click N ext >.
♦ Fill in the complete path to your bean or click
Browse to navigate to your bean. If you have created
a jar file from within your project, the path to the
exact location of the newly created Jar file is set by
default.
♦ Select the container to which you want to deploy.
♦ Click on N ext >.
♦ If you want to take an extra look at the deployment
descriptor, select the E dit-button; otherwise, click on
F inish to complete the deployment.
JBuilder™
11
Our bean is now deployed in to its runtime environment.
Step 8. Creating an Enterprise JavaBean
Client Application
In this step, we are going to create the Client Application.
We could create a client with a nice user interface but
since we only want to see whether the Bean works and
how we are able to use it, we will go for a character-
based user interface. In JBuilder 4 there is an extra wizard
called “EJB Test Client”, which can be found on the
Enterprise tab of the “Object Gallery” ( F ile, N ew).
If we start this wizard, it will pop up a single window that
asks which Enterprise JavaBean we want to test and some
class and package information for the test client. Since
there is only one Enterprise JavaBean in our project, the
default values are the correct ones, so we press OK.
The wizard has generated the whole framework of
client application for us.
All we want the client to do for us is:
1. Create a product bean (“JBuilder Foundation”, $50,00)
2. Get the name of this product (“JBuilder Foundation”)
3. Get the price of this product ($50,00)
4. Set a new price of this product ($0,00)
5. Find the product bean
6. Remove the bean
These calls to the Enterprise JavaBean are all available in
the test client, including logging information per method.
So we switch to the main method at the bottom of the
clients source code and add our code right after the
construction of the client. The main method should look
something like this:
/**Main method*/
public static void main(String[] args) {
ProductBeanTestClient1 client =
new ProductBeanTestClient1();
String prodName = "JBuilder foundation";
client.create(prodName, 50f);
client.getName();
client.getPrice();
client.setPrice(0f);
client.findByPrimaryKey(prodName);
try {
client.product.remove();
} catch
}
Step 9. Running the Enterprise JavaBean
In step 7, we have deployed the Enterprise JavaBean to
the Inprise Application Server and, in step 8, we have
created the EJB Test Client. We are now ready to test our
Enterprise JavaBean. We can either run our Enterprise
JavaBean by starting the Inprise Application Server
containing hosting the bean we have deployed in step 6,
or we can right-click the EJB group (Product.ejbgrp) and
select the run or debug option from the pop-up menu.
JBuilder™
12
JBuilder will know that this is an Enterprise JavaBean and
will start an EJB configuration for us, meaning the EJB
group will be started within a container hosting all
desired services. To make changes to this configuration,
go to the project properties dialog (menu P roject -
Project Pr o perties…) and switch to the Run tab. We see
there are four default runtime configurations:
1) Application, 2) Applet, 3) JSPTM/Servlet, and 4)
Enterprise JavaBean. We see which WM-parameters are
used, which services are started, the name of the
container, and which jars are included:
Note! If the container is run in JBuilder, the Smart
Agent™ has to be started before the container.
Note! If the Smart Agent is not started on the default
portnumber (14000), software that relies on the Smart
Agent (like the container and the EJB client) have to be
provided the following parameter for the JVM:
-Dvbroker.agent.port=<portnumber> For port 15000 the
parameter should be -Dvbroker.agent.port=15000.
This parameter is case-sensitive.
Step 10. Running the Test client
In this step, we will start the client. Running the client
can be done by using a preset Runtime Configuration, or
by right-clicking the client application class and selecting
the run option.
(Read the white paper “Getting Started, Creating your
first EnterpriseJava Bean, Stateless Session Bean” by
Gerard van der Pol and Michael Faisst on how to set
runtime configurations).
The output of our client should look something like this:
-- Initializing bean access.
-- Succeeded initializing bean access.
-- Execution time: 4867 ms.
-- Calling create(JBuilder Foundation, 50.0)
-- Succeeded: create(JBuilder Foundation, 50.0)
-- Execution time: 4086 ms.
-- Return value from create(JBuilder Foundation, 50.0 ...
-- Calling findByPrimaryKey(JBuilder Foundation)
-- Succeeded: findByPrimaryKey(JBuilder Foundation)
-- Execution time: 10 ms.
-- Return value from findByPrimaryKey(JBuilder Founda
...
-- Calling getName()
-- Succeeded: getName()
-- Execution time: 80 ms.
-- Return value from getName(): JBuilder Foundation.
-- Calling getPrice()
-- Succeeded: getPrice()
-- Execution time: 110 ms.
-- Return value from getPrice(): 50.0.
-- Calling setPrice(0.0)
-- Succeeded: setPrice(0.0)
-- Execution time: 90 ms.
Now that we have a fully functional client, we are ready
to extend the client to a more advanced look and feel.
This, however, will be out of the scope of this document.
The EJB Entity Bean modeler
There is one final thing we have not touched yet. As
mentioned in Step 2 of this document, there is a simpler
JBuilder™
13
way of creating an Entity Bean. We will discuss how in
this chapter. The way we are going to develop our bean in
this chapter will replace step 2 and step 3 of this
document.
Note! If you have no table available, you can create one
by using the “DataStore Explorer” from the tools menu.
Start the “EJB Entity Bean modeler” by selecting F ile -
N ew EJB Entity Bean modeler.
The wizard will first ask us for a EJB group. We will first
create an EJB group by clicking on the N ew… button.
This will pop up a dialog for our EJB Group. Let’s call it
QuickProduct and click on OK.
In the EJB wizard we see the newly created EJB group
selected and click on next. This will bring up the second
page of the EJB wizard. In this page we enter information
about the database we are going to use. In this case, we
will create the database connection by hand. If you have
already connected to this database from within JBuilder,
that connection information can be used by clicking on
the “ C hoose existing Connection” button.
Navigate to that database/table which contains the table
you are going to use as source for your entity bean.
Enter the information that corresponds to your database.
Browse to the database file by clicking the […] button at
the right of the URL field).
Enter the U s ername and P assword for our database. For
JDataStore the user is “scott” and the password is “tiger”.
When selecting N ext > the wizard will try to connect to
the database using the entered information.
In the next window it will show a list of available tables
in the database. Select the table you want to use as the
source for your Enterprise JavaBean and click on the
button with the greater-than(“>”) symbol to move it to the
list of selected tables.
Click on N ext >.
In this window we see the fields of our table. Make sure
they are all selected (in the right list).
Click on N ext >.
JBuilder™
14
This brings us to the page where we have to specify the
primary key.
Click on N ext >.
In the next dialog we will provide the following
information;
The bean = QuickProduct
JNDI Bean name = Product
Home interface = productentitybean.QuickProductHome
Remote interface = productentitybean.QuickProduct
Bean class = productentitybean.QuickProductBean
Click on N ext >.
Set the Entity bean type to Container managed
persistence and the Code style to EJB 1.1 style.
Click on the F inish button and continue at step 4.
JBuilder™
15
Congratulations!You have now created, deployed, and invoked your First
Enterprise Java Container Managed Persistent Bean.
This would be a good time to expand your background
knowledge on Enterprise JavaBean (and other Java 2
Enterprise Edition features) development and see how
Borland Technology can facilitate you in developing your
robust and scalable enterprise applications as well as
managing it from a distributed application point of view
using Borland® AppCenter™.
See the websites mentioned in the Additional
information chapter at the beginning of this document
for background information.
100 Enterprise WayScotts Valley, CA 95066-3249www.borland.com | 831-431-1000 | Fax: 831-431-4113
Copyright © 2000 Inprise Corporation. All rights reserved. All Inprise and Borlandbrands and product names are trademarks or registered trademarks of InpriseCorporation. Java is a trademark or registered trademark of Sun Microsystems, Inc. inthe U.S. and other countries. CORBA is a trademark or registered trademark of ObjectManagement Group, Inc. in the U.S. and other countries. 11602.1
JBuilder™
16