Enterprise Javabeans Developer's Guide 1997
Enterprise Javabeans Developer's Guide 1997
Developer’s Guide
Borland ®
™
VERSION 6 JBuilder
Borland Software Corporation
100 Enterprise Way, Scotts Valley, CA 95066-3249
www.borland.com
Refer to the file DEPLOY.TXT located in the redist directory of your JBuilder product for a complete list of files that
you can distribute in accordance with the JBuilder License Statement and Limited Warranty.
Borland Software Corporation may have patents and/or pending patent applications covering subject matter in this
document. Please refer to the product CD or the About dialog box for the list of applicable patents. The furnishing of
this document does not give you any license to these patents.
COPYRIGHT © 1997–2001 Borland Software Corporation. All rights reserved. All Borland brand and product names
are trademarks or registered trademarks of Borland Software Corporation in the United States and other countries.
All other marks are the property of their respective owners.
For third-party conditions and disclaimers, see the Release Notes on your JBuilder product CD.
Printed in the U.S.A.
JBE0060WW21004entjb 3E3R1001
0102030405-9 8 7 6 5 4 3 2 1
PDF
Contents
Chapter 1 Chapter 4
Introduction 1-1 Setting up the target application
Documentation conventions . . . . . . . . . . . 1-1 server 4-1
Note to Macintosh users . . . . . . . . . . . . 1-3 The created libraries . . . . . . . . . . . . . . . . 4-3
Contacting Borland developer support . . . . . 1-4 Adding application server files to your
Online resources . . . . . . . . . . . . . . . . 1-4 project . . . . . . . . . . . . . . . . . . . . . . . 4-4
World Wide Web . . . . . . . . . . . . . . . . 1-4 Making the ORB available to JBuilder . . . . . . 4-4
Borland newsgroups . . . . . . . . . . . . . . 1-5 Selecting an application server . . . . . . . . . . 4-4
Usenet newsgroups . . . . . . . . . . . . . . 1-5 Setting up JDBC drivers . . . . . . . . . . . . . . 4-5
Reporting bugs . . . . . . . . . . . . . . . . . 1-5 Creating the .library and .config files . . . . . 4-6
Adding the JDBC driver to projects . . . . . . 4-7
Chapter 2
Programming for the Java™ 2 Chapter 5
Platform, Enterprise Edition 2-1 Creating EJB 2.0 components with
Why are J2EE applications desirable? . . . . . . 2-1 JBuilder 5-1
Benefits of the multi-tier model. . . . . . . . 2-3 Introducing EJB modules . . . . . . . . . . . . . 5-1
How JBuilder can help . . . . . . . . . . . . . . 2-5 Creating an EJB 2.0 module . . . . . . . . . . 5-2
Client tier technologies . . . . . . . . . . . . 2-5 Creating a module with the EJB
Middle-tier technologies. . . . . . . . . . . . 2-6 Module wizard . . . . . . . . . . . . . . . 5-2
Other J2EE technologies . . . . . . . . . . . . 2-7 Creating an EJB module from
Preparing to deploy J2EE applications . . . . 2-8 existing deployment descriptors . . . . . 5-4
Learning about J2EE . . . . . . . . . . . . . . . . 2-8 Displaying the EJB Designer. . . . . . . . . . . . 5-5
Creating session beans . . . . . . . . . . . . . . . 5-7
Chapter 3 Viewing a bean’s source code . . . . . . . . . . . 5-8
An introduction to EJB development 3-1 Modifying the bean . . . . . . . . . . . . . . . . . 5-9
Why we need Enterprise JavaBeans . . . . . . . 3-1 Editing bean attributes . . . . . . . . . . . . . 5-9
Roles in the development of an EJB Adding a new field . . . . . . . . . . . . . . . 5-9
application . . . . . . . . . . . . . . . . . . . . 3-2 Removing a field . . . . . . . . . . . . . . 5-10
Application roles . . . . . . . . . . . . . . . . 3-2 Adding a new method . . . . . . . . . . . . 5-10
Infrastructure roles . . . . . . . . . . . . . . . 3-3 Removing a method . . . . . . . . . . . . 5-11
Deployment and operation roles . . . . . . . 3-4 Creating message-driven beans . . . . . . . . . 5-12
EJB architecture . . . . . . . . . . . . . . . . . . 3-4 Creating entity beans . . . . . . . . . . . . . . . 5-13
The EJB server . . . . . . . . . . . . . . . . . 3-5 Creating entity beans from an
The EJB container. . . . . . . . . . . . . . . . 3-5 imported data source . . . . . . . . . . . . 5-13
How an enterprise bean works . . . . . . . . 3-6 Importing a data source . . . . . . . . . . 5-13
Types of enterprise beans . . . . . . . . . . . . . 3-7 Modifying the imported data
Session beans . . . . . . . . . . . . . . . . . . 3-7 source schema . . . . . . . . . . . . . . 5-15
Entity beans . . . . . . . . . . . . . . . . . . . 3-7 Generating the entity bean classes
Message-driven beans . . . . . . . . . . . . . 3-7 and interfaces. . . . . . . . . . . . . . . 5-17
Remote and local access . . . . . . . . . . . . . . 3-8 Editing entity bean properties . . . . . . 5-17
Developing enterprise beans . . . . . . . . . . . 3-8
i
Creating entity bean relationships . . . . . . 5-23 Changing the build properties for a bean. . . 8-3
Using the relationship inspector to Compiling . . . . . . . . . . . . . . . . . . . . 8-4
specify a relationship . . . . . . . . . . . 5-24 The generated JAR file . . . . . . . . . . . . . . . 8-4
Removing a relationship . . . . . . . . . . 5-27 Editing deployment descriptors. . . . . . . . . . 8-5
Adding a finder method . . . . . . . . . . . . 5-28 Verifying descriptors . . . . . . . . . . . . . . 8-6
Adding an ejbSelect() method . . . . . . . . 5-28
Adding a home business method. . . . . . . 5-29 Chapter 9
Exporting a data source . . . . . . . . . . . . 5-30 Testing an enterprise bean 9-1
Removing beans . . . . . . . . . . . . . . . . 5-30 Creating a test client . . . . . . . . . . . . . . . . 9-1
How the EJB Designer names EJB files . . . . . 5-30 Using the test client application . . . . . . . . . . 9-4
Fixing errors in your bean . . . . . . . . . . . . 5-31
Testing your enterprise bean. . . . . . . . . . . . 9-5
Viewing the deployment descriptors . . . . . . 5-32
Preparing to debug WebSphere
Displaying the Deployment Descriptor
applications remotely . . . . . . . . . . . . . . . 9-8
editor. . . . . . . . . . . . . . . . . . . . . . 5-32
Setting IDE options for the EJB Designer . . . . 5-33
Taking the next step . . . . . . . . . . . . . . . . 5-33
Chapter 10
Deploying enterprise beans 10-1
Chapter 6 Creating a deployment descriptor file . . . . . 10-2
Creating EJB 1.x components with The role of the deployment descriptor . . . . . 10-2
The types of information in the
JBuilder 6-1 deployment descriptor . . . . . . . . . . . 10-3
Introducing EJB modules . . . . . . . . . . . . . 6-1 Structural information. . . . . . . . . . . 10-4
Creating an EJB 1.x module . . . . . . . . . . 6-2 Application assembly information. . . . 10-5
Creating an EJB 1.x module with Security . . . . . . . . . . . . . . . . . . . 10-5
the EJB Module wizard . . . . . . . . . . 6-2 Application server-specific
Creating an EJB module from existing
properties . . . . . . . . . . . . . . . . . 10-6
enterprise beans. . . . . . . . . . . . . . . . 6-3
Creating an EAR file . . . . . . . . . . . . . . . 10-6
Creating an enterprise bean. . . . . . . . . . . . 6-4
Deploying to an application server . . . . . . . 10-7
Creating a session bean . . . . . . . . . . . . 6-6
Deploying one or more JAR files . . . . . . 10-7
Creating an entity bean . . . . . . . . . . . . 6-7
Deploying to non-Borland servers. . . . . . 10-8
Adding the business logic to your bean . . . 6-9
Setting deployment options with
Exposing business methods through
the remote interface . . . . . . . . . . . . . 6-11 the Properties dialog box . . . . . . . . . . 10-8
Generating the bean class from a remote Hot deploying to an application server . . . 10-9
interface . . . . . . . . . . . . . . . . . . . . . . 6-12
Creating the home and remote interfaces Chapter 11
for an existing bean . . . . . . . . . . . . . . . 6-14 Using the Deployment Descriptor
editor 11-1
Chapter 7 Displaying the Deployment Descriptor
Creating EJB 1.x entity beans editor . . . . . . . . . . . . . . . . . . . . . . . 11-2
from an existing database table 7-1 Viewing the deployment descriptor of
Creating entity beans with the EJB Entity an enterprise bean. . . . . . . . . . . . . . . . 11-2
Bean Modeler . . . . . . . . . . . . . . . . . . . 7-1 Changing bean information . . . . . . . . . . . 11-4
Enterprise bean information . . . . . . . . . . . 11-5
Chapter 8 General panel . . . . . . . . . . . . . . . . . 11-5
Message Driven Bean panel . . . . . . . . . 11-8
Compiling enterprise beans and Environment panel . . . . . . . . . . . . . . 11-9
creating JAR files 8-1 EJB References panel . . . . . . . . . . . . .11-10
Compiling the bean . . . . . . . . . . . . . . . . 8-1 Resource references panel . . . . . . . . . .11-12
Changing build properties for an EJB Security Role References panel . . . . . . .11-13
module. . . . . . . . . . . . . . . . . . . . . 8-1
ii
Properties panel . . . . . . . . . . . . . . . 11-14 Writing the session bean class . . . . . . . . . . 13-2
Security Identity panel. . . . . . . . . . . . 11-18 Implementing the SessionBean
EJB Local References panel . . . . . . . . . 11-20 interface. . . . . . . . . . . . . . . . . . . . 13-2
Resource Env Refs panel. . . . . . . . . . . 11-21 Writing the business methods . . . . . . . . 13-3
Server-specific Properties panel . . . . . . 11-22 Adding one or more ejbCreate()
Container transactions . . . . . . . . . . . . . 11-23 methods. . . . . . . . . . . . . . . . . . . . 13-3
Setting container transaction policies . . . 11-23 How JBuilder can help you create a
WebLogic 6.x Transaction Isolation session bean . . . . . . . . . . . . . . . . . 13-4
panel . . . . . . . . . . . . . . . . . . . . . 11-25 The life of a session bean . . . . . . . . . . . . . 13-6
Working with data sources . . . . . . . . . . . 11-26 Stateless beans . . . . . . . . . . . . . . . . . 13-6
Setting isolation levels . . . . . . . . . . . . 11-28 Stateful beans . . . . . . . . . . . . . . . . . 13-6
Setting data source properties . . . . . . . 11-28 The method-ready in transaction
Adding security roles and method state . . . . . . . . . . . . . . . . . . . . 13-8
permissions . . . . . . . . . . . . . . . . . . . 11-30 A shopping cart session bean . . . . . . . . . 13-10
Creating a security role . . . . . . . . . . . 11-31 Examining the files of the cart example. . 13-10
Assigning method permissions . . . . . . . 11-31 The Cart session bean . . . . . . . . . . . . .13-11
Adding container-managed persistence Adding the required methods . . . . . 13-12
information for EJB 1.1 components . . . 11-34 Adding the business methods . . . . . 13-13
Finders panel . . . . . . . . . . . . . . . . . 11-35 Item class . . . . . . . . . . . . . . . . . . . 13-15
Specifying WebSphere 4.0 finders. . . . 11-37 Exceptions . . . . . . . . . . . . . . . . . . 13-15
Verifying descriptor information . . . . . . . . 11-38 Required interfaces . . . . . . . . . . . . . 13-16
The home interface . . . . . . . . . . . 13-16
Chapter 12 The remote interface . . . . . . . . . . . 13-17
Using the DataExpress for The Cart deployment descriptor . . . . 13-18
EJB components 12-1 Chapter 14
The DataExpress EJB components . . . . . . . . 12-2
Components for the server . . . . . . . . . . 12-2 Developing entity beans 14-1
Components for the client . . . . . . . . . . . 12-2 Persistence and entity beans . . . . . . . . . . . 14-1
Creating the entity beans . . . . . . . . . . . . . 12-2 Bean-managed persistence . . . . . . . . . . 14-2
Creating the server-side session bean . . . . . . 12-3 Container-managed persistence . . . . . . . 14-2
Adding provider and resolver Primary keys in entity beans. . . . . . . . . . . 14-2
components to the session bean. . . . . . . 12-3 Writing the entity bean class . . . . . . . . . . . 14-3
Writing the setSessionContext() method. . . 12-4 Implementing the EntityBean interface . . . 14-4
Adding an EJB reference to the Declaring and implementing the
deployment descriptor . . . . . . . . . . 12-5 entity bean methods. . . . . . . . . . . . . 14-5
Adding the providing and resolving Creating create methods . . . . . . . . . 14-5
methods . . . . . . . . . . . . . . . . . . . . 12-5 Creating finder methods . . . . . . . . . 14-7
Calling the finder method . . . . . . . . . . . 12-6 Writing the business methods . . . . . . 14-7
Building the client side . . . . . . . . . . . . . . 12-7 The life of an entity bean . . . . . . . . . . . . . 14-8
Handling relationships . . . . . . . . . . . . . . 12-9 The nonexistent state . . . . . . . . . . . . . 14-8
The sample project . . . . . . . . . . . . . . . . . 12-9 The pooled state . . . . . . . . . . . . . . . . 14-8
The ready state. . . . . . . . . . . . . . . . . 14-9
Chapter 13 Returning to the pooled state . . . . . . . . 14-9
A bank entity bean example . . . . . . . . . . 14-10
Developing session beans 13-1 The entity bean home interface . . . . . . 14-10
Types of session beans. . . . . . . . . . . . . . . 13-1
The entity bean remote interface. . . . . . .14-11
Stateful session beans . . . . . . . . . . . . . 13-1
An entity bean with container-
Stateless session bean . . . . . . . . . . . . . 13-2
managed persistence . . . . . . . . . . . .14-11
iii
An entity bean with bean-managed Chapter 17
persistence. . . . . . . . . . . . . . . . . . 14-13
The primary key class . . . . . . . . . . . . 14-18
Developing enterprise bean clients 17-1
Locating the home interface . . . . . . . . . . . 17-2
The deployment descriptor . . . . . . . . . 14-18
Getting the remote/local interface . . . . . . . 17-2
Deployment descriptor for an
Session beans . . . . . . . . . . . . . . . . . 17-2
entity bean with bean-managed
Entity beans . . . . . . . . . . . . . . . . . . 17-3
persistence . . . . . . . . . . . . . . . . 14-20
Finder methods and the primary
Deployment descriptor for an
key class . . . . . . . . . . . . . . . . . . 17-3
entity bean with container-
Create and remove methods . . . . . . . 17-4
managed persistence . . . . . . . . . . 14-20
Calling methods. . . . . . . . . . . . . . . . . . 17-4
Removing bean instances . . . . . . . . . . . . 17-5
Chapter 15 Referencing a bean with its handle . . . . . . . 17-6
Developing message-driven beans 15-1 Managing transactions . . . . . . . . . . . . . . 17-7
How message-driven beans work . . . . . . . . 15-2 Discovering bean information . . . . . . . . . . 17-8
The life of a management-driven bean Creating a client with JBuilder . . . . . . . . . 17-9
instance . . . . . . . . . . . . . . . . . . . . . . 15-2
Writing a message-driven bean class . . . . . . 15-3 Chapter 18
Implementing the
MessageDrivenBean interface. . . . . . . . 15-4
Managing transactions 18-1
Characteristics of transactions . . . . . . . . . . 18-1
Implementing the MessageListener
Transaction support in the container . . . . . . 18-2
interface . . . . . . . . . . . . . . . . . . . . 15-4
Enterprise beans and transactions . . . . . . . 18-3
Writing the onMessage() method . . . . . 15-4
Bean- versus container-managed
How JBuilder can help you create a
transactions. . . . . . . . . . . . . . . . . . 18-3
message-driven bean . . . . . . . . . . . . . 15-5
Local and global transactions . . . . . . . . 18-4
Message-driven bean deployment
Using the transaction API . . . . . . . . . . . . 18-5
descriptor attributes . . . . . . . . . . . . . . . 15-6
Handling transaction exceptions . . . . . . . . 18-6
Using the SonicMQ Message Broker
System-level exceptions . . . . . . . . . . . 18-7
with message-driven beans . . . . . . . . . . . 15-7
Application-level exceptions . . . . . . . . . 18-7
Handling application exceptions . . . . . . 18-7
Chapter 16 Transaction rollback . . . . . . . . . . . . 18-8
Creating the home and remote/local Options for continuing a transaction . . 18-8
interfaces 16-1
Creating the home interface . . . . . . . . . . . 16-1 Appendix A
The EJBHome interface . . . . . . . . . . . . 16-2 Creating JMS producers and
The LocalHome interface . . . . . . . . . . . 16-2
Creating a home or local home interface
consumers A-1
Using the JMS wizard . . . . . . . . . . . . . . A-2
for a session bean . . . . . . . . . . . . . . . 16-3
Publish\subscribe message systems . . . . A-3
create() methods in session beans . . . . . 16-3
Point to point message systems . . . . . . . A-4
Creating a remote home or local home
Completing the code . . . . . . . . . . . . . . . A-5
interface for an entity bean . . . . . . . . . 16-4
create() methods for entity beans . . . . . 16-5
Finder methods for entity beans . . . . . 16-5
Index I-1
Creating the remote or local interface . . . . . . 16-7
The EJBObject interface . . . . . . . . . . . . 16-8
iv
Chapter
1
Introduction
Chapter1
Documentation conventions
The Borland documentation for JBuilder uses the typefaces and symbols
described in the table below to indicate special text.
There are special considerations on the Macintosh platform. Please see
“Note to Macintosh users” on page 1-3 for more information.
Introduction 1-1
Documentation conventions
Introduction 1-3
Contacting Borland developer support
Online resources
You can get information from any of these online sources:
Borland newsgroups
You can register JBuilder and participate in many threaded discussion
groups devoted to JBuilder.
You can find user-supported newsgroups for JBuilder and other Borland
products at http://www.borland.com/newsgroups/
Usenet newsgroups
The following Usenet groups are devoted to Java and related
programming issues:
• news:comp.lang.java.advocacy
• news:comp.lang.java.announce
• news:comp.lang.java.beans
• news:comp.lang.java.databases
• news:comp.lang.java.gui
• news:comp.lang.java.help
• news:comp.lang.java.machine
• news:comp.lang.java.programmer
• news:comp.lang.java.security
• news:comp.lang.java.softwaretools
Note These newsgroups are maintained by users and are not official Borland
sites.
Reporting bugs
If you find what you think may be a bug in the software, please report it in
the JBuilder Developer Support page at http://www.borland.com/
devsupport/jbuilder/. From this site, you can also submit a feature
request or view a list of bugs that have already been reported.
When you report a bug, please include all the steps needed to reproduce
the bug, including any special environmental settings you used and other
programs you were using with JBuilder. Please be specific about the
expected behavior versus what actually happened.
If you have comments (compliments, suggestions, or issues) with the
JBuilder documentation, you may email [email protected]. This is for
documentation issues only. Please note that you must address support
issues to developer support.
JBuilder is made by developers for developers. We really value your
input, because it helps us to improve our product.
Introduction 1-5
1-6 Enterprise JavaBeans Developer’s Guide
Chapter
the client resided in a database and was “served up” by a server. This
approach initially promised improved scalability and functionality.
In the multi-tier model, the logic involved in presenting the user interface
of the application to the user lives on the middle tier. The business logic is
now on the middle tier also. When changes are needed, they can be
updated in one place instead of on each client machine.
This expanded diagram shows you the various components you might
find running on the various tiers:
The business logic of the application runs in the middle tier running in
an Enterprise JavaBean (EJB) container and/or on a web server. These
containers and servers can handle many of the difficult tasks for
developers. For example, an EJB container can handle transactions,
instance pooling, and data persistence without requiring the EJB
programmer to write the logic to perform these tasks. A web server can
create and pool instances of servlet classes and handle multiple threads
and socket connections. Instead of writing the code to do these things, a
member of the development team specifies the desired behavior at
deployment time.
Members of the development team play different roles. Each is a
specialist in one or more areas. For example, the content of an HTML
page or stylesheet would likely be created by a graphic designer or
webmaster. A senior developer might be responsible for the business
logic of the application encapsulated within Enterprise JavaBean
components. A web developer might develop the user interface and
presentation logic using JavaServer Pages (JSPs) and servlets. An
application assembler takes the various components of the application
and puts it all together, often creating an Enterprise Archive (EAR) file
and creating the deployment descriptor that explains how the
application is to be deployed. The application deployer and
administrator deploy the application. By partitioning the work this
way, each step of the development/deployment process is handled by
someone skilled in their area while no one has to be an expert in every
area.
• It is highly scalable allowing the development of systems to meet many
different needs that can change quickly.
When demands on the system increase, the logic can be updated easily
in one place on the middle tier without having to load new logic on
every client machine.
• New applications can integrate well with existing information systems.
JDBC, a J2EE technology, is a Java API to SQL databases, permitting the
access to any type of tabular data that might exist in the enterprise. The
Java Naming and Directory Interface (JNDI) allows applications that
use Java technology to access enterprise naming and directory services.
The developing J2EE Connector architecture will give Java applications
connections to heterogeneous legacy systems. The Java Message
Service (JMS) is the Java API for sending and receiving messages
though enterprise messaging systems. CORBA services are called using
JavaIDL.
• Security is enhanced.
J2EE technologies are designed with security in mind. For example,
only users in assigned roles can access certain methods in enterprise
beans. Who can access these methods isn’t coded in the enterprise
Middle-tier technologies
These are the middle-tier J2EE technologies that use a web server:
• Servlets
A servlet is a server-side Java application that can process requests
from clients. The servlet responds to the request by generating dynamic
output that is sent back to the client. You can begin developing servlets
with JBuilder’s Servlet wizard. To find out more about servlets and
developing them, see “Working with servlets” in the Web Application
Developer’s Guide.
• JavaServer Pages (JSPs)
An extension of servlet technology, JSPs offer a simplified way to
develop servlets. Like servlets, they generate dynamic output that is
sent back to the client’s web browser. Begin developing JSPs with
JBuilder’s JavaServer Page wizard. To find out more about JSPs and
developing them, see “JavaServer Pages (JSP)” in the Web Application
Developer’s Guide.
InternetBeans Express is a component library that supplements the
servlet and JSP technology available in JBuilder. This library makes it
easy to present and manipulate data from a database so you can build
data-aware servlets and JSPs.
This is the middle-tier J2EE technology that uses an EJB container:
• Enterprise JavaBeans (EJBs)
Enterprise JavaBeans are server-side components that contain the
business logic of the application. JBuilder assists you in building EJB 1.x
and EJB 2.0 components. Start building enterprise beans by using the
EJB wizards on the EJB page of the object gallery (File|New|EJB). For
building EJB 2.0 components, JBuilder offers the EJB Designer, a
Two-Way Tool™ that allows you to design your beans visually all the
while keeping your code, deployment descriptors, and design
synchronized. For more information about building, testing, and
deploying enterprise beans, see Chapter 3, “An introduction to EJB
development.”
As you create your enterprise beans, JBuilder is building your EJB
deployment descriptors. You can use JBuilder’s Deployment Descriptor
editor to modify them as you wish. For more information about the
Deployment Descriptor editor, see Chapter 11, “Using the Deployment
Descriptor editor.”
All the web application components and enterprise bean components can
be combined and delivered in an EAR (Enterprise Archive) file. JBuilder
has an EAR wizard to help you create your EAR files.
An introduction to EJB
Chapter3
3
development
The “Enterprise JavaBeans (EJB) specification” formally defines a Java
server-side component model and a programming interface for
application servers. Developers build the components, called enterprise
beans, to contain the business logic of the enterprise. Enterprise beans run
on an EJB server that provides services such as transaction management
and security to the beans. Developers don’t have to worry about
programming these low-level and complex services, but can focus on
encapsulating the business rules of an organization or system within the
beans, knowing that the services are available to the beans when they are
needed.
While the Enterprise JavaBeans specification is the ultimate authority on
the EJB framework, it’s primarily useful to vendors such as Borland who
build the EJB servers and containers the beans run in. This book will help
you, the JBuilder developer, learn what you want to know about
developing enterprise beans with JBuilder.
Gradually the benefits of dividing applications into more than the two
tiers of the client-server model becomes apparent. In a multi-tier
application, only the user interface stays on local machines while the logic
of the application runs in the middle tier on a server. The final tier is still
the stored data. When the logic of an application needs updating, changes
are made to the software of the middle tier on the server, greatly
simplifying the management of updates.
But creating reliable, secure, and easily managed distributed applications
is notoriously difficult. For example, managing transactions over a
distributed system is a major task. Fortunately, using components that
follow the EJB specification to build distributed systems relieves much of
the burden by:
• Dividing the development of a distributed system into specific tasks
that are assigned to specialists.
For example, if the application is an accounting system, the enterprise
bean developer would need to understand accounting. The system
administrator must know about monitoring a deployed and running
application. Each specialist assumes a particular role.
• Making EJB server and container services available to the enterprise
bean and application developers.
The EJB server provider and EJB container provider (who are often the
same vendor) handle many of the more difficult tasks so the developers
don’t have to. For example, the container an enterprise bean runs in can
provide transaction and security services to the bean automatically.
• Making enterprise beans portable.
Once a bean is written, it can be deployed on any EJB server that
adheres to the Enterprise JavaBeans standard. Each bean is likely to
include vendor-specific elements, however.
Application roles
Those who assume the application roles write the code for the enterprise
beans and the applications that use them. Both roles require an
Infrastructure roles
Without a supporting infrastructure, the enterprise beans and the
applications that use them cannot run. Although the two infrastructure
roles are distinct, they are almost always assumed by the same vendor.
Together they provide system-level services to the enterprise beans and
provide an environment in which to run. These are the two infrastructure
roles:
• EJB server provider
EJB server providers are specialists in distributed transaction
management, distributed objects, and other low-level services. They
provide an application framework in which to run EJB containers. EJB
service providers must provide, at a minimum, a naming service and a
transaction service to the beans.
• EJB container provider
EJB container providers provide the deployment tools required to
deploy enterprise beans and the runtime support for the beans. A
container provides management services to one or more beans. They
communicate for the beans with the EJB server to access the services the
bean needs.
In almost all cases, the EJB server provider and the EJB container provider
are the same vendor. The Borland Enterprise Server provides both the
server and the container.
EJB architecture
Multi-tier distributed applications often consist of a client that runs on a
local machine, a middle-tier that runs on a server that contains the
business logic, and a backend-tier consisting of an enterprise information
system (EIS). An EIS can be a relational database system, an ERP system, a
legacy application, or any data store that holds the data that needs to be
accessed. This figure shows a typical EJB multi-tier distributed system
with three tiers: the client; the server, the container, and the beans
deployed on them; and the enterprise information system.
Because our interest is how to develop enterprise beans, our focus is the
middle tier.
Session beans
Session beans can be either stateful or stateless. Stateless beans don’t
maintain state for a particular client. Because they don’t maintain
conversational state, stateless beans can be used to support multiple
clients.
A stateful session bean executes on behalf of a single client. In a sense, the
session bean represents the client in the EJB server. Stateful session beans
can maintain the client’s state, which means they can retain information
for the client. The classic example where a session bean might be used is a
shopping cart for an individual shopping at an online store on the web. As
the shopper selects items to put in the “cart,” the session bean retains a list
of the selected items.
Session beans can be short-lived. Usually when the client ends the session,
the bean is removed by the client.
Entity beans
An entity bean provides an object view of data in a database. Usually the
bean represents a row in a set of relational database tables. An entity bean
usually serves more than one client.
Unlike session beans, entity beans are considered to be long-lived. They
maintain a persistent state, living as long as the data remains in the
database, rather than as long as a particular client needs it.
The container can manage the bean’s persistence, or the bean can manage
it itself. If the persistence is bean-managed, the bean developer must write
code that includes calls to the database.
Message-driven beans
The EJB 2.0 specification introduced message-driven beans. They behave
as a Java Message Service (JMS) listener, processing asynchronous
messages. The EJB container manages the bean’s entire environment.
3 Select the Borland Enterprise Server 5.0 page and specify the directory
where the Borland Enterprise Server 5.0 is installed. This is usually in
the /BorlandEnterpriseServer directory.
You must close and then restart JBuilder to enable the EJB wizards. If you
want to make the VisiBroker ORB available to JBuilder, you can wait until
you complete that step before shutting down and restarting JBuilder.
4 Select the application server you are building your beans to run on. The
Borland Enterprise Server 5.0 is the default server.
The Generic AppServer 1.0 choice is a generic option. It represents a
basic application server that supports EJB 1.1 and/or EJB 2.0
development. Select it if the application server you use is not currently
supported by JBuilder. You will probably want to edit the resulting
deployment descriptor with tools supplied with that application server
to get the exact settings you want. You could also choose this option if
the you aren't targeting a specific application server.
5 Choose OK to close the dialog box.
Important If you make changes to the .library file after the .config file has been
derived, you must re-generate the .config file using Enterprise Setup, then
restart JBuilder.
Now that JBuilder can see the database driver, you must add the database
driver library to the Required Libraries list in Project|Properties, or
Project|Default Properties.
Once you have an EJB module and have edited it to your liking with the
Deployment Descriptor editor, you can Make or Build an EJB module to
produce the JAR. JBuilder uses the deployment descriptor to help identify
the class files to be packaged.
An EJB module can be one of two formats: XML or binary. Because an EJB
module in XML format is essentially a text file, it’s easier to work with if
you are using a version control system. An EJB module in binary format is
essentially the deployment descriptors in a .zip archive.
You can have more than one EJB module in a project. All the EJB modules
in a single project use the same project classpath and JDK, and they are
configured for the same target application server.
If you haven’t done so already, follow the instructions in Chapter 4,
“Setting up the target application server.” You must follow the steps to
add a library containing your application server files to each EJB project
you undertake.
module, the EJB Designer, the project pane, and the structure pane would
look like this:
7 Click Finish to create the EJB module that contains the deployment
descriptors for the existing bean(s).
• Use the EJB 2.0 Designer wizard. These are the steps you follow:
1 Choose File|New, click the Enterprise tab, and double-click the EJB
2.0 Designer.
2 Select the EJB module you want the bean you create to become part
of from the list of Available EJB Modules.
Only the available EJB 2.0 modules appear in the list. If you don’t
have a module yet, you can choose the New button, which starts the
EJB Module wizard. When the wizard completes, the EJB 2.0
Designer wizard continues.
3 Click OK.
The EJB Designer appears. For example, if you are starting a project
named BeansProject and you specified MyBeanModule as the name
of the EJB module, the EJB Designer, the project, pane, and the
structure pane would look like this:
3 Within the inspector, change the name of the bean to a name of your
choosing.
The files in the project pane are renamed to reflect the name change.
4 Use the Interfaces drop-down list to select from Remote, Local, or
Remote/Local.
Selecting Remote means that the EJB Designer generates the bean class
with a remote home and remote interface. This is the default value.
Selecting Local means that the EJB Designer generates a bean class with
a local home and a local interface. Because the EJB Designer generates
the Remote interfaces by default for session beans, selecting Local
changes the name and content of the bean’s files in the project pane to
reflect a bean that can be accessed locally only. The local home interface
name will have LocalHome appended to it, and local interface name will
have Local appended to it.
If you select the Remote/Local option, all the remote and local files will
appear in the project pane giving you a total of five bean files.
5 Specify the type of session bean in the Session Type field: Stateless or
Stateful.
6 Specify the Transaction Type: Container (for container-managed) or
Bean (for bean-managed).
7 If you want the bean to implement the SessionSynchronization interface,
set the Session Synchronization attribute to true. This option is
available for stateful session beans only. For more information about
the SessionSynchronization interface, see “The SessionSynchronization
interface” on page 13-8.
8 Click the Classes And Packages button to make any changes to the
package name, bean name, interface names, and bean class name. Click
OK.
Changes you make appear in the project pane.
Removing a field
To remove a field from a bean, right-click the field in the bean
representation and choose Remove Field.
Removing a method
To remove a method from a bean, right-click the method in the bean
representation and choose Remove Method.
The EJB Designer attempts to connect to the specified data source. If the
attempt to connect succeeds, the specified data source appears in the
structure pane:
4 Open the new node in the structure pane to see the tables in the data
source you have imported:
• For table nodes, use the context menu to add a column to the table, edit
table properties, or to rename or delete the table node from the data
source.
For help understanding the meaning of these properties, click the Help
button in the dialog box.
• For column nodes, use the context menu to edit column properties, or
to rename or delete the column node from the table.
Choose Edit Column Properties to change the data type of the column
and specify if the column is a primary key. These properties are specific
to the Borland application servers only:
For help understanding the meaning of these properties, click the Help
button in the dialog box.
The Bean Properties in the inspector determine the name of the bean,
allow you to specify a different name for your schema, establish the names
of the bean classes and interfaces and where they are located, and
determine whether the bean has remote interfaces (home and remote),
local interfaces (local home and local, or both the remote and local
interfaces (home, remote, local home, and local).
Click the Properties button to view the CMP Properties:
ejb.maxBeansInCache
Specifies the maximum number of beans in the Option A cache (see
ejb.transactionCommitMode which follows). If the cache exceeds this
limit, entities will be moved to the ready pool by calling ejbPassivate().
The default setting is 1000.
ejb.maxBeansInPool
Specifies the maximum number of beans in the ready pool. If the ready
pool exceeds this limit, entities are removed from the container. The
default setting is 1000.
ejb.transactionCommitMode
Indicates the disposition of an entity bean with respect to a transaction.
The values are:
• A or Exclusive — This entity has exclusive access to the particular table
in the database. Thus, the state of the bean at the end of the last
committed transaction can be assumed to be the state of the bean at the
beginning of the next transaction. The beans are cached across
transactions.
2 Use the right drop-down list to specify the table you want to reference:
Click and hold down the mouse button on a column in the left table you
want to link to a column in the right table. Drag a line to the column
you want to link to:
If you need a third table to make the connection between two tables as
you might in a many to many relationship, click the Add Cross Table
button and select the table that has fields that can be used to link to
both tables. Then click and drag between the columns of the three
tables to complete the table reference.
3 In the entity bean representation, click one of the fields you want to
map to a column in the referenced table to display its field inspector.
4 In the Column Name drop-down list, select the column you want to
map the field to:
2 Give the new group a name in the Field Group Name field.
3 Check the fields you want to be included in the group.
4 Click OK.
Use the inspector to change the field name, if you wish. You can specify
the field’s type, specify whether its value will be persisted, specify
whether the field is a primary key for the table, specify if you want the
field’s value set in the ejbCreate() method in the bean class, specify where
the field’s access methods are defined, and map the field to the
appropriate column in the table.
The method inspector for entity beans is the same one used for session
and message-driven beans. See “Adding a new method” on page 5-10 if
you want more detail.
If the two tables have one or more columns with the same name, the table
reference editor will show lines drawn between the common columns of
the two tables. If no common column names exists, you must draw a line
between the columns you want to use to create the relationship. For
example, if the Department table had a column called DEPT_NO, and the
Employee table had a column called DEPT, you would click and drag from the
DEPT_NO column of the Department table to the DEPT column of the Employee
table. When you release the mouse button, a line appears between the two
columns, indicating the relationship.
For many-to-many relationships you need a third table to make the
connection between two tables. For example, you might have an Employee
table that includes a column named EMP_NO. You might also have a Project
table that includes a column named PROJ_ID. By themselves, the two tables
have no columns you can use to create a relationship directly. If you had a
Employee-Project table that consisted of two columns, EMP_NO and PROJ_ID,
you could create a relationship between the Employee and Project table. In
this case, in the table reference editor, you would click the Add Cross
Table button. From the drop-down list that appears between the two
tables, you would select the table that contains the columns to make the
connection between the two tables. In this case, you would select the
Employee-Project table. Then you would click and drag between the EMP_NO
columns of the Employee table and the Employee-Project table, and do the
same between the PROJ_ID columns of the Project table:
Click OK when you are done with the Edit Table Reference editor to
return to the new field’s inspector. You can use this inspector to specify if
the relationship is one to one, one to many, or many to many.
You can also specify whether the relationship is unidirectional or
bidirectional. If you select bidirectional, a new field also appears in the
second bean. For example, if you have a Employee entity bean and a Project
entity bean, you might want to create a relationship that allows an
employee to have multiple projects as well as keeping track of all the
employees on a single project. In this case, the direction of the relationship
is bidirectional. Therefore, the Employee bean will have a new field named
project, and the Project bean will have a new field named employee.
Use the CMR Field Properties in the inspector to specify in which
interface(s) the getter and setter access methods are declared. The Return
Type is the return type of the getter method and the type of the parameter
passed to the field’s setter method.
Click the Edit RDBMS Relation button to display the WebLogic RDBMS
Relation Editor. If, in the relationship inspector you specified the
Multiplicity as One to One or One to Many, the editor looks like this:
If you specified Many to Many as the value of the Multiplicity field, the
editor looks like this:
In this case, you select the table in the middle that contains the columns
that join the other two tables. Then click and drag between the columns
that establish the relationship:
Removing a relationship
To remove a relationship between two entity beans, right-click the new
field that was added to the entity bean when the relationship was created
and choose Remove Relationship on the context menu.
Removing beans
To remove one or more EJBs from the EJB Designer,
1 Select the bean representation in the EJB Designer:
• To select a single bean, click it.
• To select multiple beans, Ctrl-click each bean you want to select.
2 Right-click one of the selected beans and choose Remove Selected EJBs
or press the Delete key.
If you do the same thing for an entity bean with the same name of
Component, these are the files the EJB Designer generates for you:
• ComponentHome — the local home interface
• ComponentBean — the bean class
• Component — the local interface
• ComponentRemoteHome — the remote home interface
• ComponentRemote — the remote interface
3 Make your selections to change the screen elements as you wish and
click OK when you are done.
You can have more than one EJB module in a project. All the EJB modules
in a single project use the same project classpath and JDK, and they are
configured for the same target application server.
If you haven’t done so already, follow the instructions in Chapter 4,
“Setting up the target application server.” You must follow the steps to
add one or more libraries containing your application server files to each
EJB project you undertake.
7 Click Finish to create the EJB module that contains the deployment
descriptors for the existing bean(s).
The Enterprise JavaBean 1.x wizard and the EJB Entity Bean Modeler
create the home and remote interfaces at the same time the bean class is
created. If you prefer to begin your enterprise bean development by
creating your remote interface first, see “Generating the bean class from a
remote interface” on page 6-12 for information about using the EJB 1.x
Bean Generator to generate your bean class from a remote interface you
have created.
To begin creating an enterprise bean with the Enterprise JavaBean 1.x
wizard,
1 Choose File|New and click the Enterprise tab.
2 Double-click the Enterprise JavaBean 1.x wizard icon.
The wizard appears.
3 In the drop-down list, select the EJB module you want your enterprise
bean to belong to. Choose Next to display page 2 of the wizard.
If you don’t have an EJB module defined before you start the Enterprise
JavaBeans wizard or you want to create another, click the New button
to start the EJB Module wizard. You must have at least one EJB module
defined in your project before you can create an enterprise bean. Once
you’ve created an EJB module with the EJB Module wizard, select the
new module and choose Next to continue with the Enterprise JavaBean
1.x wizard.
4 Specify the class name of your bean class, the package it will be in, and
the bean’s base class.
Next you must decide whether you are creating a session bean or an entity
bean.
4 Specify names for the Home Interface Class, the Remote Interface Class,
and the Bean Home Name; JBuilder suggests default names based on
the name of your bean class.
5 Click Finish.
4 Specify names for the Home Interface Class, the Remote Interface Class,
and the Bean Home Name; JBuilder suggests default names based on
the name of your bean class.
5 Click Finish.
After you click the Finish button, JBuilder creates the bean class and its
home and remote interfaces. You’ll see them appear in the project pane.
Examine the source code of the bean class and you’ll see that the class
implements the SessionBean interface if it’s a session bean, and it
implements the EntityBean interface if it’s an entity bean. JBuilder has
added methods with empty bodies for the methods all enterprise beans
must implement. You can add code to these method bodies to supply the
logic your bean requires when these methods are called.
The home interface extends the EJBHome interface and contains a create()
method needed to create the bean. The remote interface extends EJBObject
but is empty otherwise because you have yet to declare any business logic
methods for your bean.
Although you can begin your entity beans using the Enterprise JavaBeans
wizard, the preferred way to create entity beans is to use the EJB 1.x Entity
Bean Modeler. Entity beans you create with the Enterprise JavaBean 1.x
wizard aren’t likely to pass verification with the Deployment Descriptor
editor until you complete the bean more fully.
Note For WebSphere 4.0 Advanced Edition, the mapping descriptors aren’t
generated at this phase. When you build your bean, EjbDeploy, which is
called during the build process, will generate them for you. You can then
modify the mapping and run Make again to keep the mapping in the JAR.
Note For WebSphere 4.0 Single Server, the mapping descriptors are not generated.
As you check methods in the Methods box, the methods are added to the
remote interface.
To remove a method from the remote interface, uncheck the check box
next to the method in the Methods box.
To edit one of the methods, right-click it to display a context menu and
choose Edit Selected. The file opens in the code editor and your cursor is
positioned on that method, ready for you to edit it.
The context menu has other commands you’ll find useful. You can choose
Remove Selected to remove a method from the bean class. Choosing
Check All checks all the methods so that they are all added to the remote
interface; choosing Uncheck All unchecks all the methods so that no
methods are added to the remote interface.
You can use the Methods page to verify that the methods declared in your
bean class have the same method signature as they do in the home and
3 Select the EJB module the bean belongs to and click Next.
4 Select the type of EJB you want generated and click Next.
If you selected one of the session bean options, this page appears:
Specify the EJB Bean Options: the Bean Class, the Bean Name, the
Home Interface, and the JNDI Name.
If you selected the CMP entity bean option, this screen appears:
Specify the EJB Bean options: the Bean Class, the Bean Name, the Home
Interface, the JNDI Name, the Primary Key Class, and which fields you
want to be persistent.
5 Choose Finish.
The EJB 1.x Bean Generator creates the skeleton bean class you specified
that includes the methods found in the remote interface. In the generated
bean class, these methods include a comment reminding you to fill in their
implementations. You must add your code to the methods to implement
them as you wish.
The EJB 1.x Bean Generator also creates a home interface if one did not
previously exist. If a home interface did exist, the EJB 1.x Bean Generator
asks you if you want to overwrite the home interface and responds
according to your answer.
3 Select the EJB module the bean belongs to and click Next.
This page appears if the bean is a session bean:
7 Leave those methods that you want exposed in the remote interface
checked and uncheck those you don’t want to appear in the remote
interface.
8 Choose Finish.
Your next step is to compile your beans, debug them, and create a JAR file.
See Chapter 8, “Compiling enterprise beans and creating JAR files.”
Creating EJB 1.x entity beans from an existing database table 7-1
Creating entity beans with the EJB Entity Bean Modeler
To display the EJB Entity Modeler, choose File|New, click the Enterprise
tab, and choose EJB Entity Bean Modeler. If you have at least one EJB
module defined in your project, the Entity Bean Modeler appears.
All enterprise beans developed with JBuilder must belong to an EJB module.
If you don’t have at least one EJB module in your current project, click the
New button to start the EJB Module wizard. Once you’ve created an EJB
module with the EJB Module wizard, the Entity Bean Modeler then appears.
To create one or more beans from existing database tables, follow these
steps:
1 Select an EJB module to put your bean in and choose Next to go to Step 2.
The EJB module you select is used to determine where the deployment
information is written.
Creating EJB 1.x entity beans from an existing database table 7-3
Creating entity beans with the EJB Entity Bean Modeler
5 Select the columns from each table to map to entity bean fields and
specify any relationships you want to establish between the tables.
In the Tables and Links section, you’ll see all the tables you selected in
the previous step. Select each table in turn by clicking on it and then use
the Selected Table’s Columns section to move any columns of the table
between the Available and Selected lists. By default, all columns in
every table are selected.
You can also specify relationships between the tables by dragging the
mouse pointer between the tables in the Tables and Links box on the
left. Or you can use the Add Link button to do the same thing. When
you use either method, a dialog box appears that proposes a
relationship based on foreign keys, primary keys, unique indexes, and
field names and types in the two tables. You can accept the suggested
relationship or modify it to create the relationship you want. To remove
a link between tables, choose Remove Link.
When you’ve selected all columns in each table that you want mapped
to fields in entity beans you’re creating, choose Next.
6 Specify the names and data types for the entity bean fields to map to
your table’s columns.
Click the appropriate tab to select the table you want to begin the
mapping process on. For each column in the table a suggested Field
Name and Field Type appears. You can simply accept the suggested
name or edit the suggested names and types as you want them to be in
your bean.
To change the data type of multiple fields at one type, select the fields
you want to change and choose Update Field Type. A dialog box
Creating EJB 1.x entity beans from an existing database table 7-5
Creating entity beans with the EJB Entity Bean Modeler
appears in which you can type the new field type. When you choose
Apply or OK, the field type for each selected field changes.
If the table already has a primary key, that field or set of fields is
selected when the Map Columns page first appears. If no primary key
exists, you must select one or more fields to make up primary key by
checking the check box for those fields in the Primary Key column.
When you finish mapping all the selected columns to the field names
and types you want in your entity bean for each table, choose Next.
7 Specify the package, the classes and interfaces, and the JNDI name for
each bean you are creating.
For each table, JBuilder suggests a name for the entity bean, the name
used by JNDI, the name of the home and remote interfaces, the name of
the bean class, and the type of the primary key class. You can specify a
different package for each of these; by default, the project package is
suggested. You can accept these values as they are, or you can modify
them as you wish. When you have finished specifying the information
for each table, choose Next.
Creating EJB 1.x entity beans from an existing database table 7-7
Creating entity beans with the EJB Entity Bean Modeler
also includes a Pool Name field in which you should enter the name of
the pool for your CMP WebLogic beans:
9 Choose Finish.
JBuilder creates an entity bean for each table and all the supporting classes
interfaces. You can now add the business logic you want to the beans,
define the methods you want the client to be able to call in the remote
interface, compile the beans, and edit the deployment descriptors for the
beans.
Note For container-managed support for the WebSphere 4.0 Advanced Edition,
the map and schema deployment descriptor files (Map.mapxmi and
Schema.dbxmi) are standard descriptors generated by the EjbDeploy utility,
which is called during the build process. If you choose to change the
default CMP field names, types, or lengths in the Entity Bean Modeler
wizard, you must edit the schema file by hand to change the field names,
types, or lengths accordingly:
1 Generate the entity beans using the Entity Bean Modeler wizard.
2 Compile your project. This generates the map and schema deployment
descriptor files.
3 Click the DD Source tab to edit the Schema.dbxmi file to change the
column names, field types, or field lengths to match the database
column names, field types, or field lengths.
4 Recompile the module to create the JAR using the modified file.
Note For WebSphere 4.0 Single Server, the mapping descriptors are not
generated.
option is not checked, you can still create the JAR by right-clicking the
EJB module and choosing Make or Rebuild.
5 Click the tab of the application server you are targeting. For example,
this image shows the Borland Enterprise Server 5.0 tab selected:
6 Specify the build options you want. If you need more information
about the available options, click the Help button.
7 Click OK when you are done.
Compiling
To compile all the classes in the project, right-click the project file
(<project>.jpx) and choose Make, or simply choose Project|Make Project.
During the compiling process, JBuilder might detect that a problem exists
in a deployment descriptor that makes it invalid. If this happens, you’ll
see a message appear in the message pane that tells you to verify the bean
in the Deployment Descriptor editor. For more information about
verifying a deployment descriptor, see “Verifying descriptor information”
on page 11-38.
Note for WebLogic If you are targeting the WebLogic Server, you’ll receive an error during
users the build process if the temporary directory or the classpath contains
embedded spaces, such as C:/Documents and Settings/jbprojects.
If you’ve chosen to generate the clients stubs, you’ll see that the home
interface node in the project pane now has several files listed below it if
you click its icon to expand it. These generated files are the required client
stubs and helper classes that make enterprise beans work.
The build process is customized for the target application server and runs
the tools specific to that application server in addition to compiling the
.java files.
Note for WebSphere Two deployment descriptors (Map.mapxmi and Schema.dbxmi are generated
4.0 users for entity beans with container-managed persistence for the WebSphere
4.0 Advanced Edition only. If you are using one edition of WebSphere 4.0
and change your target server to the other version, you must recompile
your project to ensure JBuilder generates the correct deployment
descriptors for you.
The JAR file contains all the deployment descriptors. Each deployment
descriptor is an XML file, except for WebSphere 3.5, which uses a .ser file for
each bean. Each JAR file can contain one or more deployment descriptors.
JBuilder will target one of multiple application servers. The application
server you are targeting determines the number of deployment
descriptors that are in the generated JAR file. Every JAR file will have an
ejb-jar.xml (except for those that target WebSphere 3.5), which describes
the deployment attributes for the beans in the module that are common
among all application servers. ejb-jar.xml is the EJB 1.1- or
EJB 2.0-compliant deployment descriptor.
All vendor-specific information for an EJB 2.0- module is kept in the
ejb-borland.xml file, even when the application server is some other than a
Borland server. For EJB 1.1 modules, the file name is ejb-inprise.xml. When
you compile, additional vendor-specific XML files are generated from this
information. They are also generated when you click the Deployment
Descriptor editor Source tab. If WebSphere 3.5 is your target application
server, the generated JAR file will contain a .ser file for each bean.
Verifying descriptors
After you’ve finished editing the descriptor, you can verify the file to
make sure the descriptor information is correct, the required bean class
files are present, and so on.
To verify descriptor information, right-click the module in the project
pane and choose Verify.
Verify does the following:
• Ensures that the descriptor conforms to the EJB 1.1 or 2.0 specification,
depending on the type of the EJB module.
• Ensures that the classes referenced by the deployment descriptors conform
to the EJB 1.1 or 2.0 specification, depending on the type of the EJB module.
If the verification fails, one or more messages appear in a Log panel
describing the failures.
2 Choose File|New, click the Enterprise tab and double-click the EJB Test
Client icon.
3 Select the bean you want to create a client for using one of the Select EJB
options and specifying the bean:
• Select From Project if your bean is in the current project and specify
which bean by selecting it from the drop-down list.
• Select From JAR Or Directory if your bean is not in the current
project, but exists elsewhere in a JAR file or a directory. Use the ...
button to navigate to where the JAR is located and select the JAR,
then use the drop-down list to select the bean you want.
Note You will see only EJBs with remote interfaces in these lists because
enterprise beans with local interfaces cannot be accessed by a client
application, only by another bean or a web component.
4 Select the package name from the list of packages. The current package
is the default value.
5 Enter a name for the test client class or accept the default name.
6 Select the options you want:
• Generate Method For Testing Remote Interface Calls With Default
Arguments
Adds a testRemoteCallsWithDefaultArguments() method that tests the
remote interface calls with default argument values. For example,
the default argument for a String is ““, the default argument for an
int is 0, and so on.
• Generate Logging Messages
Adds code that displays messages reporting on the bean’s status as
the client runs. For example, a message is displayed when bean
If you prefer to write the logic that calls each of the business methods from
another class, you can choose to create and use an instance of the test
client application. See “Using the test client application” on page 9-4.
Compile your test client application.
3 If the test client already exists, check the EJB Test Client Class Already
Exists option.
If this option isn’t checked, when you click Next, the EJB Test Client
wizard starts. When you are through using it, the Use EJB Test Client
wizard resumes.
4 Click Next to go to Step 2.
5 For the Class field, navigate to the test client class you want to use.
6 In the Field field, specify a name for the variable that will hold an
instance of the test client class, or accept the default value the wizard
suggests.
7 Choose Finish.
The wizard adds a declaration of the test client application you specified
to the class like this, for example:
EmployeeTestClient1 employeeTestClient1 = new EmployeeTestClient1();
Now you’re ready to call the methods declared in the test client
application.
2 Click the New button and then click the EJB tab.
4 Click the ... button next the Main Class field and navigate to the test
client application you created, or to the application containing the
main() function that calls the methods of the test client.
5 If your target application server is Borland Enterprise Server 5.0, enter
-Dvbroker.agent.port=<port no.> in the VM Parameters field, entering
the port number that the Visibroker Smart Agent uses.
6 Click OK two times.
For Borland Enterprise Server 5.0 users, you must now start Smart Agent.
Choose Tools|VisiBroker Smart Agent.
Now you’re ready to start the container. Select the Server run configuration
from the drop-down list next to the Run button on the JBuilder toolbar:
The container starts up. Be patient as the start-up process takes a while.
You can view the progress of the start-up process in the message window.
Any errors that occur will also appear there.
Next select the Client run configuration to run your client application. The
messages that appear in the message pane report the success or failure of
the client application’s execution.
You can also modify the deployment descriptor once the enterprise bean
is deployed.
The information in the deployment descriptor is used in setting enterprise
bean attributes. These attributes define how the enterprise bean operates
within a particular environment. For example, when you set the bean’s
transactional attributes, they define how the bean behaves with respect to
transactions. The deployment descriptor keeps the following information:
• Type information, which defines the types, or names, of the classes for
the home/local home and remote/local interfaces and the bean class.
• JNDI names, which set the name under which the home/local home
interface of the enterprise bean is registered.
• Fields to enable container-managed persistence.
• Transactional policies that govern the transactional behavior of a bean.
• Security attributes that govern access to an enterprise bean.
• Borland-specific information, such as data source information used for
connections to a database.
Structural information
The bean developer must provide the following structural information for
each bean in the EJB JAR file:
Session beans
• Session bean’s home and/or local home interface
• Session bean’s remote and/or local interface
• Session bean state management type, either stateful or stateless
• Session bean transaction demarcation type for stateful beans that have
synchronization callbacks
Entity beans
• Entity bean’s home and/or local home interface
• Entity bean’s remote and/or local interface
• Entity bean’s persistence management type
• Entity bean’s primary key class
• Container-managed fields for container-managed beans
Message-driven beans
• Message-driven bean’s transaction management type
• Message-driven bean’s destination and subscription durability
Security
The application assembler usually specifies the following information in
the deployment descriptor:
• Security roles
• Method permissions
• Links between security role references and security roles
• Security identity
Security roles
Using the security role elements in the deployment descriptor, the
developer can define one or more security roles. These define the required
security roles for the clients of the enterprise beans.
Method permissions
Using the method-permission elements in the deployment descriptor, the
developer can define method permissions. Method permissions are paired
relations between the security roles and the methods of the enterprise
bean’s remote/local and remote home/local home interfaces.
For information on using the EAR wizard, click the Help button.
When you finish using the wizard, it creates an .eargrp node in the project
pane. Double-clicking this node displays an EAR DD Source tab in the
content pane that displays the EAR’s deployment descriptors.
To create an EAR file from the .eargrp node, right-click it and choose
Make. Now when you expand the .eargrp node, you’ll can see new EAR
file in the project pane.
The wizard searches for running containers and lists all it finds.
2 From the Target Partition list, select your target partition of the
application server to which you want to deploy.
3 Click the Add button to navigate to the location of the J2EE modules
(JAR, WAR, and EAR files) you want to deploy and select them. Choose
OK.
4 If you want to verify that the deployment descriptors and the classes
they reference are correctly formed before the modules are deployed,
check the Verify Deployment Descriptors option.
5 If you have not yet generated the stubs for your beans and want to do
so, check the Generate Stubs option.
6 The wizard has an Advanced Options button. It allows you to set
additional Container Discovery, Stub Generator, and Verifier options.
If you want to modify any of these options, click Advanced Options,
and use the Advanced Options dialog box that appears to make your
changes. Choose OK when you are done.
7 Click OK to close the wizard and begin the deployment process.
The wizard attempts to deploy the J2EE module(s) and reports the
results.
The deployment tool for WebSphere 4.0 differs depending on the version
of the server you are using. For the Single Server, WebSphere’s
deployment tool is XmlConfig. For the Advanced Edition, the deployment
tool is SEAppInstaller. Therefore, the appearance of the Deploy Settings
dialog box will vary between these two WebSphere Server 4.0 editions.
Fill in the fields you need and choose OK. For more information, click the
Help button in the Deploy Settings dialog box.
the values you entered then become the default values for the EJB module
node.
To set deployment options using the Properties dialog box,
1 Right-click the EJB module node, a child JAR of this node, or an EAR
group to display the context menu.
2 Choose Properties to display the Properties dialog box. If you
right-clicked the EJB module node, you must now click the Deployment
tab of the Properties dialog box and then the page specific to your
application server (such as the Borland Enterprise Server).
3 Set your options. The options available will vary depending your target
application server. For example, for Borland Enterprise Server 5.0, you
can set the host name, the container, and VM parameters. WebLogic
users can set a unit name, deploy options, a password, and VM
parameters. WebSphere users can set the primary node name, the
application server name, the container name, VM parameters, and an
option to generate XML. If multiple nodes are selected that have
different deploy options, default values are used. Consult your
application server’s documentation for assistance in filling in these
fields.
4 If your target application server is WebSphere 3.5 or WebSphere 4.0
Advanced Edition and you want an XML file to be generated as input
to the WebSphere XMLConfig utility, check the Generate XML check
box. If this option isn’t checked, the file won’t be created. If you make
your own modifications to the generated XML file (named
deploy_<selectednode>.xml and appearing under the EJB module node or
EAR group), uncheck this option to be sure you don’t lose your
changes. If you use the Deployment Options on the context menu
(right-click the EJB module and choose Deployment Options <jar
name>.jar to see the deployment commands), the generated XML file is
deploy.xml. It appears under the project node.
The Deployment Descriptor has many other tabs. You can click any of
these tabs at the bottom of the Deployment Descriptor editor to view other
panels. Use the editor to make any changes you want to the deployment
information for the bean.
You can view additional information about a deployment descriptor by
opening a bean node in the project pane. By double-clicking these nodes,
you can see additional panels. For example, double-clicking the Container
Transactions node for a bean displays a Container Transactions panel in
the Deployment Descriptor editor. The JDBC DataSources and Security
Roles nodes can also be opened, if they contain data. The subnodes that
appear can be used to display more information.
To view the source code of each descriptor, double-click the EJB module
node in the project pane, then click the EJB DD Source tab at the bottom of
the Deployment Descriptor editor. For each deployment descriptor in the
EJB module, a tab appears with the name of the file on the tab. Select the
tab of the file you want to view. While viewing the source code of a
deployment descriptor, you can click on elements in the structure pane to
move a highlight bar to the corresponding element in the source code. You
can edit the source code directly.
General panel
Use the General panel to enter or change general information about the
enterprise bean.
This is the General panel for a session bean:
and a remote interface. This field is available for EJB 2.0 components
only.
• JNDI Name: The JNDI name of the enterprise bean’s remote home
interface.
• Local JNDI Name: The local JNDI name of the enterprise bean’s local
home interface. This field is available for EJB 2.0 components only.
• Description: A summary of the bean’s purpose and function. This
information is optional.
• Small icon: The name of a 16 X 16 pixel icon file used to represent the
bean.
• Large icon: The name of a 32 X 32 pixel icon file used to represent the
bean.
For Session beans, the General panel also includes the following:
• Session Type: Specifies whether the enterprise bean is Stateless or
Stateful.
• Transaction Type: Specifies whether Transaction Policies are set by the
bean or the container.
For Entity beans, the General panel also includes the following:
• Persistence Type: Specifies whether the bean’s persistence is managed
by the bean itself or the container. For entity beans created with the EJB
Designer, the Persistence Type must be Container.
• CMP Version: Specifies whether the container-managed persistence
used is version 1.1 or 2.0. This field is available just for EJB 2.0 entity
beans. Also, for entity beans created with the EJB Designer, the CMP
Version must be 2.0.
• Primary Key Class: The fully-qualified name of the Entity bean’s
primary key class. The primary key class must be specified.
• Reentrant: Indicates the bean is reentrant. Borland recommends you
avoid making a bean reentrant.
The following fields are available on the Message Driven Bean panel:
• Transaction Type: Specifies the bean’s transaction management type.
Choose Bean if the bean manages its own transactions; choose
Container if the container manages the transaction handling.
• Acknowledge Mode: This field appears only if the Transaction Type
value is Bean. The Auto-acknowledge option means that all messages
the bean receives are acknowledged and a check is performed to
prevent acting on duplicate messages. The Dups-ok-acknowledge
means that all messages are acknowledged, including duplicate
messages if they should occur.
• Message Selector: The message selector that determines which
messages the message-driven bean should receive. Here is an example:
JMSType = ‘chair’ AND color = ‘black’ AND fabric = ‘leather’
See the JMS specification on Sun Microsystems’ web site at
http://java.sun.com/products/jms/docs.html for more information.
• Message Driven Destination: Indicates whether a message-driven
bean is intended for a Queue or a Topic. You can also select Not
Specified. If you select Topic, the Subscription Durability field appears.
• Subscription Durability: Indicates whether the bean’s subscription to a
topic is durable or nondurable. This field is available only if you
selected Topic as the value of the Message Driven Destination field.
• Destination Name: The JNDI name of the queue or topic to which the
message-driven bean listens. This is the JMS destination from which the
message-driven bean instance consumes messages.
• Initial Pool Size: The initial number of message-driven bean instances
the container should create immediately after deployment.
• Maximum Pool Size: The maximum number of message-driven bean
instances that can be created and kept in the message-driven bean
instance pool.
• Connection Factory Name: The JNDI name of the connection factory
that is used to establish a connection to the message broker.
Environment panel
The Environment panel lists all the enterprise bean’s environment entries.
Environment entries allow you to customize the bean’s business logic
when the bean is assembled or deployed. The environment allows you to
customize the bean without accessing or changing the bean’s source code.
Each enterprise bean defines its own set of environment entries. All
instances of an enterprise bean share the same environment entries.
Enterprise bean instances aren’t allowed to modify the bean’s
environment at runtime.
To add a resource reference, click the Add button and fill in the following
fields:
• Description: A description of the resource reference. This information
is optional.
• Name: The name of the environment entry used in the enterprise
bean’s code.
• Type: The Java type of the resource factory expected by the enterprise
bean’s code. (This is the Java type of the resource factory, not the Java
type of the resource.)
• Authentication: An Application authentication indicates that the
enterprise bean performs the resource sign-on programmatically. A
Container authentication indicates that the container signs on to the
resource based on the principal mapping information supplied by the
deployer.
• Sharing Scope: Determines whether the resource can be shared. Your
options are Shareable and Unshareable. This field is available for EJB
2.0 components only.
• JNDI Name: JNDI name for the resource reference.
Before you can add a security role reference, one or more security roles
must be already defined or the Add button on this panel is disabled. For
information about creating and assigning security roles for application
deployment, see “Adding security roles and method permissions” on
page 11-30.
To add a role, click the Add button and fill in the three fields:
• Description: This is an optional field that describes the security role.
• Role: This is the name of the security role specified by the bean
developer.
• Link: This is the name of the security role used when the application is
deployed. Usually, this role is defined by the application assembler or
deployer to work in a specific operating environment.
Properties panel
When you double-click an enterprise bean in the project pane and click the
Properties tab in the Deployment Descriptor editor, the following
Properties pane appears:
Use this panel only if your target application server is a Borland server.
To add a property to an enterprise bean selected in the project pane,
1 Click the Add button to add a row to the panel.
2 From the Name drop-down list, select the property you want to add.
ejb.cmp.checkExistenceBeforeCreate
Suppresses the existence check that occurs before creating a new entity
bean. The EJB specification requires that the container first check for the
existence of an entity bean (that is, check for the existence of a row in
the table) and throw a javax.ejb.DuplicateKeyException if such an entity
is found. For performance reasons, you might want to eliminate this
extra access to the database and rely on the fact that the database will
prevent duplicate values from being inserted.
ejb.cmp.findByPrimaryKeyLoadState
Indicates whether to load the non primary key values when executing
the findByPrimaryKey() method (the default) or to simply verify that the
entity’s record exists in the database. This flag is equivalent to the
<load-state>attribute on other finders.
ejb.cmp.getPrimaryKeyBeforeInsertSql
Specifies the SQL the CMP engine executes to generate a primary key
when the next INSERT occurs. The CMP engine updates the entity bean
with this primary key value. This property is usually used in
conjunction with Oracle Sequences. For more information about
primary key generation, see the
/BorlandEnterpriseServer/examples/ejb/pkgen example.
ejb.cmp.getPrimaryKeyAfterInsertSql
Specifies the SQL the CMP engine executes to generate a primary key
after the next INSERT. The CMP engine updates the entity bean with
this primary key value. When specifying this property, you must also
specify the ejb.cmp.ignoreColumnsOnInsert property. For more
information about primary key generation, see the
/BorlandEnterpriseServer/examples/ejb/pkgen example.
ejb.cmp.ignoreColumnsOnInsert
Specifies the name of the column the CMP must not set during the
INSERT. This property is used in conjunction with the
ejb.cmp.getPrimaryKeyAfterInsertSql property. For more information
about primary key generation, see the
/BorlandEnterpriseServer/examples/ejb/pkgen example.
ejb.cmp.jdbcAccesserFactory
Specifies a factory for a user-implemented instance of the
com.inprise.ejb.cmp.JdbcAccessor interface. This interface gives you a
way to write specific code to get a value from a java.sqlResultSet or to
set a value to a java.sql.PreparedStatement. The default value is none.
ejb.cmp.manager
Specifies the name of a class implementing the interface
com.inprise.ejb.cmp.Manager. An instance of this class is used to perform
container-managed persistence (CMP).
ejb.cmp.primaryKeyGenerator
Specifies a class, written by the user, that implements the
com.inprise.ejb.cmp.PrimaryKeyGenerator interface and generates primary
keys. For more information about primary key generation, see the
/BorlandEnterpriseServer/examples/ejb/pkgen example.
ejb.maxBeansInPool
Specifies the maximum number of beans in the ready pool. If the ready
pool exceeds this limit, entities will be removed from the container by
calling unsetEntityContext(). The default setting is 1000.
ejb.maxBeansInCache
Specifies the maximum number of beans in the Option A cache (see
ejb.transactionCommitMode which follows). If the cache exceeds this
limit, entities will be moved to the ready pool by calling ejbPassivate().
The default setting is 1000.
ejb.maxBeansInTransaction
Limits the total number of entity beans that may be held by the
container in transactions. This property is useful when running very
large transactions (batch transactions) that involve a great number of
entities. Usually entities are kept in the transaction until the transaction
completes. For batch transactions, however, hanging on to all the
entities associated with the transaction might possibly exhaust the
virtual machine’s memory.
ejb.transactionCommitMode
Indicates the disposition of an entity bean with respect to a transaction.
The values are:
A or Exclusive — This entity has exclusive access to the particular table
in the database. Thus, the state of the bean at the end of the last
committed transaction can be assumed to be the state of the bean at the
beginning of the next transaction. The beans are cached across
transactions.
B or Shared —This entity shares access to the particular table in the
database. However, for performance reasons, a particular bean remains
ejb.cmp.optimisticConcurrencyBehavior
You can specify one of the following:
• UpdateAllFields
• UpdateModifiedFields
• VerifyModifiedFields
• VerifyAllFields
UpdateAllFields — Issues an update on all fields, regardless of whether
they were modified. Given a CMP bean with three fields: “key”,
“value1” and “value2”, stored in a table called “MyTable”, the
following update will be issued at the end of every transaction,
regardless of whether the bean was modified:
UPDATE MyTable SET (value1 = <value1>, value2 = <value2>)
WHERE key = <key>
UpdateModifiedFields —This is the default setting. Issues an update
only on the fields that were modified, or suppresses the update
altogether if the bean was not modified. With the above bean, if only
“value1” was modified, the following update is issued:
UPDATE MyTable SET (value1 = <value1>)
WHERE key = <key>
This can give a significant performance boost for following reasons:
1 Often your data access is read—only. In such cases, not sending an
update to the database is desirable. Borland has seen great
performance boosts from this single optimization.
2 Many databases write logs depending on which columns were
modified. For example, SQL Server will log the update if a TEXT or
IMAGE field is updated, regardless of whether the column’s value
actually changed. Note that the database often does not (or cannot)
distinguish between updating a column to hold the same value it
used to hold (which is what occurs with “UpdateAllFields”), and
actually modifying the column’s value. Suppressing the update for
the case where the value did not actually change can have a very
significant performance impact when using such DBMSs.
To specify that a security identify be used when methods of the bean are
executed, check the Specify Security Identify check box and follow these
steps:
1 If you choose to do so, enter a description of the security identity in the
Description field.
2 Specify whether the caller’s security identity should be used or whether
a specific run-as security identity should be used with the drop-down
list below the Description field. If you select the Run As option, the
panel changes so that it look like this:
the JNDI name is used to find the bean. When you check this option,
you then select the bean that is referenced from the Link drop-down
list.
• Link: Links the EJB reference to the target enterprise bean. The Link
value is the name of the target bean. This information is optional.
• Type: The expected type of the referenced bean.
• Local Home: The expected Java type of the referenced bean’s local
home interface.
• Local: The expected Java type of the referenced bean’s local
interface.
• JNDI Name: The JNDI name of the referenced bean.
These are important points to remember about EJB local references:
• The target enterprise bean must be type-compatible with the declared
EJB local reference.
• All declared EJB references must be bound to the local homes of
enterprise beans that exist in the operating environment.
• If a Link value is specified, the enterprise bean reference must be bound
to the local home of the target enterprise bean.
Use this panel if you want to view and edit some of the vendor-specific
elements that are unique to your target application server. The panel
displays a table of properties specific to the server. In the right column,
enter values for properties you want to modify. The property values are
stored in the server-specific deployment descriptors.
Container transactions
Enterprise beans that use container-managed transactions must have the
transaction policies set by the container. The Deployment Descriptor
editor enables you to set container-managed transaction policies and then
associate these policies with methods in the enterprise bean’s remote
home, local home, remote, and local interfaces.
5 In the row, select the Interface that exposes the method: the home, local
home, remote, or local. Or select * to select all interfaces. Your selection
in this field determines which choices you will have in the Methods
field.
6 From the drop-down list of Methods available, select the method you
are setting the transaction isolation policy for, or select * to select all the
methods in the interface(s) you specified in the Interface field.
7 From the drop-down list, select the transaction attribute that describes
the isolation policy you want for the methods you specified. The
information found in “Setting isolation levels” on page 11-28 may help
you make your selection.
8 Enter a description in the Description field to describe the transaction.
Adding a description is optional.
Refer to your WebLogic documentation for more assistance on the setting
of isolation levels.
panel. You can use the panel to modify the information on the selected
data source. Only entity beans have a data source.
Property Description
maxBigDecimalScale If you are using JDBC 1.0, the value of this property
determines the scale to use when this method is called:
java.sql.BigDecimal java.sql.ResultSet.getBigDecimal(int
columnIndex, int scale);
If you are using JDBC 2.0, a scale value is not used when
getBigDecimal(int columnIndex) is called.
uniqueSequence Determines whether the CMP engine should declare a
unique sequence for the primary key columns. Usually
this is achieved by declaring the appropriate columns to
be primary keys (see primaryKeyDeclaration).
Property Description
batchUpdates Indicates whether the CMP engine should batch updates
to the database. This can have a significant performance
benefit for transactions that update a number of entities
that update a number of entities, and should be used if the
driver supports it. Unfortunately, most don’t support
batch updates yet. The default value is false.
useSetObjectForSetNull When a SQL column is set to null value, usually this
method is used:
void java.sql.PreparedStatement.setNull(int
parameterIndex, int sqlType);
Because some JDBC drivers do not support this, you can
set this flag to make the CMP engine use the following
method instead:
void java.sql.PreparedStatement.setObject(int
parameterIndex, Object x);
“null” becomes the value of x.
reuseStatements Determines whether the CMP engine should reuse
prepared statements across transactions. Reusing
prepared statements has a significant performance
impact, and they should be used unless the JDBC driver
exhibits are reused. The default value is true.
notNullDeclaration Determines whether the Java fields that can’t be null (such
as int or float) should map to non-null columns. The
default value is true.
dialect Determines the type of the data source, such as whether
its a JDataStore, Oracle, Informix, or other data source.
Select the dialect value from the Value drop-down list. If
you don’t set this field, the CMP engine creates tables for
JDataStore only. The default value is none.
primaryKeyDeclaration Determines whether the CMP engine declares the primary
key columns in the table to be primary keys. Some
databases don’t support primary key declarations. The
default value is true.
You can enter a description for the new role on the Security Roles panel.
The description is optional.
If your bean is an EJB 2.0 bean, the Method Permissions panel looks like
this:
Finders panel
The Finders panel specifies the “where’ clauses used by the container-
managed bean to execute finder methods defined by the bean. The Finders
panel is available for EJB 1.1 entity beans with container-managed
persistence.
To display the Finders panel,
1 Expand an EJB 1.1 entity bean node in the project pane.
Here’s an example:
Select the finder type you want. The default value is a WHERE clause
(SQL WHERE). The finder type you select is added to the WebSphere-
specific deployment descriptor ibm-ejb-jar-ext.xmi. You can then return to
the Finders panel and specify the query using the query type you selected
on the WebSphere 4.0 Properties panel as the value of the Where Clause
on the Finders panel, even if the query type is other than a WHERE clause.
Using the Inspector, set the provider and resolver properties of the
TableDataSet to the newly added EntityBeanProvider and EntityBeanResolver
components, respectively. The result is two new methods in the jbInit()
method:
employeeDataSet.setProvider(entityBeanProvider);
employeeDataSet.setResolver(entityBeanResolver);
The sample project shows these methods in the setSessionContext()
method instead. You can add the method calls yourself to
setSessionContext() if you prefer to imitate the sample project exactly.
Either approach is fine.
To the members of this class, add a reference to the home interface of the
entity bean that contains the data you want to access. For this example, the
reference is to the home interface of the Employee entity bean as shown here
in bold.
public class PersonnelBean implements SessionBean {
private SessionContext sessionContext;
EntityBeanProvider entityBeanProvider = new EntityBeanProvider();
EntityBeanResolver entityBeanResolver = new EntityBeanResolver();
TableDataSet employeeDataSet = new TableDataSet();
EmployeeHome employeeHome;
...
session bean’s remote interface to verify that the two methods are now
defined:
public interface Personnel extends EJBObject {
public com.borland.dx.dataset.DataSetData[]
providePersonnel(com.borland.dx.ejb.RowData[] parameterArray,
com.borland.dx.ejb.RowData[] masterArray) throws RemoteException;
public com.borland.dx.dataset.DataSetData[]
resolvePersonnel(com.borland.dx.dataset.DataSetData[] dataSetDataArray)
throws RemoteException;
}
...
void entityBeanProvider_findEntityBeans(EntityBeanFindEvent e) {
}
3 To the new event handler, add a finder method to return the entity
beans you want. Here the added code appears in bold:
void entityBeanProvider_findEntityBeans(EntityBeanFindEvent e) {
try {
e.setEntityBeanCollection(employeeHome.findAll());
}
catch (Exception ex) {
throw new EJBException(ex);
}
}
In this example, the event handler calls a findAll() method to return all the
entity beans. You can call any finder you want. You could use the
EntityBeanProvider’s parameterRow property to dynamically determine
which finder to call and/or which parameters to pass.
must add a creating event if you want to invoke a create() method on the
home interface that requires parameters. For example, look at this code:
import com.borland.dx.dataset.*;
import com.borland.dx.ejb.*;
public PersonnelDataModule() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
try {
sessionBeanConnection.setJndiName("Personnel");
sessionBeanConnection.addCreateSessionBeanListener(new
com.borland.dx.ejb.CreateSessionBeanListener() {
public void creating(CreateSessionBeanEvent e) {
sessionBeanConnection_creating(e);
}
});
personnelDataSet.setSessionBeanConnection(sessionBeanConnection);
personnelDataSet.setMethodName("Personnel");
}
catch (Exception ex) {
}
}
public static PersonnelDataModule getDataModule() {
if (myDM == null) {
myDM = new PersonnelDataModule();
}
return myDM;
}
public com.borland.dx.ejb.SessionBeanConnection getSessionBeanConnection() {
return sessionBeanConnection;
}
public com.borland.dx.ejb.EjbClientDataSet getPersonnelDataSet() {
return personnelDataSet;
}
void sessionBeanConnection_creating(CreateSessionBeanEvent e) {
}
}
Handling relationships
The EntityBeanProvider automatically flattens relationships. For example, if
you have any Employee entity bean that has a getDept() method that returns
a Dept, where Dept is an entity bean remote, a DataSet is created that has all
the fields in the Employee entity bean plus all the fields in the Dept entity
bean (including any hidden columns containing the primary keys of each
of the entity beans). Except for Dept.ejbPrimaryKey, the other Dept fields will
be read-only.
To resolve changes when a one-to-one relationship is involved, you must
add an event listener to the EntityBeanProvider because it can’t dynamically
determine the home of the related entity bean. The sample ejb.jpx project
does not demonstrate handling relationships.
The methods of the SessionBean interface are closely associated with the life
cycle of a session bean. This table explains their purpose:
Method Description
setSessionContext() Sets a session context. The bean’s container calls this method
to associate a session bean instance with its context. The
session context interface provides methods to access the
runtime properties of the context in which a session runs.
Usually a session bean retains its context in a data field.
ejbRemove() Notifies a session object that it is about to be removed. The
container calls this method whenever it removes a stateful
session bean as a result of the client calling a remove() method
of the remote/local or remote home/local home interface.
ejbActivate() Notifies a stateful session object that is has been activated.
ejbPassivate() Notifies a stateful session object that it is about to be
deactivated by the container.
remote interface. For stateless session beans, there can be only one
parameterless ejbCreate().
This is the signature for all ejbCreate() methods of a session bean:
public void ejbCreate( <zero or more parameters> ) {
// implementation
}
The ejbCreate() method need not throw an exception, although it can
throw application-specific exceptions and other exceptions, such
javax.ejb.CreateException. The EJB wizards generate an ejbCreate() method
that throws javax.ejb.CreateException.
Using JBuilder’s Enterprise JavaBean 1.x wizard, you can begin creating a
EJB 1.1 session bean by selecting either the Stateless Session Bean or
Stateful Session Bean option on the wizard’s second page:
Not only do JBuilder’s EJB wizards create your enterprise bean class, they
also create the bean’s home and remote/local interfaces as they create the
bean class. This way, you are assured the create() method of the home
interface returns the remote/local interface while the ejbCreate() method
always returns void.
When you write the business methods in your EJB 2.0 bean class, you use
the inspector to specify in which interface the methods are declared. The
EJB Designer then adds the correct declaration for you to the proper
interface. If you specify a home interface, the EJB Designer declares the
method as a home business method. It adds the prefix ejbHome to the
name of the method in your bean class and declares the method without
the prefix in the home interface.
After you write the business methods in your EJB 1.x bean class, you can
use the Bean designer to specify which of those you want defined in the
bean’s remote interface for an EJB 1.1 session bean. A client application
can access only those methods defined in the remote interface. Once you
specify which methods you want a client to be able to call, the Bean
designer defines the methods in the remote interface for you.
If you already have a complete enterprise bean class, but don’t have home
and remote interfaces for it, you can use JBuilder’s EJB 1.x Interfaces
wizard to create them. The method signatures will comply with EJB 1.1
specifications in the home and remote interfaces without you having to
worry about making them correct.
For more information about using JBuilder’s tools to develop EJB 1.1
session beans, see “Creating a session bean” on page 6-6.
Stateless beans
The life of a stateless session bean begins when the client calls the create()
method of the session bean’s home interface. The container creates a new
instance of the session bean and returns an object reference to the client.
Stateful beans
The life of a stateful session bean begins when the client calls the create()
method of the session bean’s home interface. The container creates a new
instance of the session bean, initializes it, and returns an object reference
to the client.
The container can deactivate the session bean instance. Usually this occurs
for resource management reasons such as when a session object is idle for
a while or if the container requires more memory. The container
deactivates the bean by calling the bean’s ejbPassivate() method. When a
bean instance is deactivated, which is called passivation, the container
stores reference information and the state of the session object on disk and
frees the memory allocated to the bean. You can add code to ejbPassivate()
if you have some task you want to execute just before passivation occurs.
The container activates the bean object again by calling the ejbActivate()
method. This occurs when the client calls a method on the session bean
that is passivated. During activation, the container recreates the session
object in memory and restores its state. If you want something to happen
immediately after the bean becomes active again, add your code to the
ejbActivate() method.
the wizard declares the three methods with empty bodies in your bean
class:
For an EJB 2.0 session bean, use the bean’s Inspector in the EJB Designer to
set the Session Synchronization attribute to true to add the
SessionSyncronization interface methods to your bean class.
The following table briefly describes each method:
Method Description
afterBegin() Notifies the bean instance that it is about to be used in a
transaction. Any code you write within afterBegin() occurs
within the scope of the transaction.
beforeCompletion() Notifies the bean instance that the transaction is about to
commit. If the bean has any cached values, use
beforeCompletion() to write them to the database. If necessary,
a session bean could use the beforeCompletion() method to
force the transaction to roll back by calling the
setRollbackOnly() method of the SessionContext interface.
afterCompletion() Notifies the bean instance that the transaction has completed.
If the transaction was committed, the parameter
completionStatus is set to true. If the transaction was rolled
back, the parameter is set to false.
This is how the SessionSynchronization methods are used: The client calls a
transactional business method defined in the remote interface, which puts
the bean object in the transaction-ready state. The container calls the
afterBegin() method in the bean object. Later, if the transaction is
committed, the container calls beforeCompletion(), and then, if the commit
was successful, the afterCompletion(true) method. If the transaction was
rolled back or otherwise failed to commit, the container calls
afterCompletion(false). The session bean object is now in method-ready
state again.
The container calls the ejbRemove() method just prior to removing the bean
instance. You can add some application-specific code that would execute
before the bean is removed, but it isn’t required. The CartBean example
leaves the body of the ejbRemove() method empty.
The getTotalPrice() method initializes the total price to zero, then loops
through the item list, adding the price of each element to the total price. It
returns the total price rounded to the nearest penny.
public float getTotalPrice() {
System.out.println("\tgetTotalPrice(): " + this);
float totalPrice = 0f;
Enumeration elements = _items.elements();
while(elements.hasMoreElements()) {
Item current = (Item) elements.nextElement();
totalPrice += current.getPrice();
}
// round to the nearest lower penny
return (long) (totalPrice * 100) / 100f;
}
All data types passed between a client and a server must be serializable.
That is, they must implement the java.io.Serializable interface. In the Cart
example, the bean returns a list of items to the client. If there were no
serializable restrictions, you could use _items.elements() to return the
contents of the item vector. But _items.elements() returns a Java Enumeration
object, which is not serializable. To avoid this problem, the program
implements a class called com.inprise.ejb.util.VectorEnumeration(_items).
This class takes a vector and returns an actual enumeration, which is
serializable, for the contents of that vector. The CartBean object passes this
serializable vector to the client, and receives a serializable vector passed
from the client side. The getContents() method does the conversion
between a Java Enumeration and a serializable VectorEnumeration.
public java.util.Enumeration getContents() {
System.out.println("\tgetContents(): " + this);
return new com.inprise.ejb.util.VectorEnumeration(_items);
}
The purchase() method should do the following:
1 Get the current time.
2 Compare the expiration date of the credit card with the current time. If
the expiration date is prior to the current time, the method throws the
CardExpiredException application exception.
3 Complete the purchasing process, including updating inventory,
posting the charge to the credit card company, and initiating shipment
of the item. (None of this has actually been implemented in the Cart
example.) If an error occurs at any point, the purchase process does not
complete and the method throws a PurchaseProblemException exception.
public void purchase() throws PurchaseProblemException {
System.out.println("\tpurchase(): " + this);
Item class
The CartBean example uses an Item class. Item is public and it extends
java.io.Serializable; serialized data can be passed on the wire:
package shoppingcart;
public class Item implements java.io.Serializable {
private String _title;
private float _price;
public Item(String title, float price) {
_title = title;
_price = price;
}
public String getTitle() {
return _title;
}
public float getPrice() {
return _price;
}
}
Exceptions
There are three exception classes in the Cart example. All are extensions of
the Java class Exception:
public class ItemNotFoundException extends Exception {
public ItemNotFoundException(String message) {
super(message);
}
}
public class PurchaseProblemException extends Exception {
public PurchaseProblemException(String message) {
super(message);
}
}
Required interfaces
Session beans always have at least two interfaces: a home and a remote or
local interface. In this example the Cart session bean has a public EJB
remote interface called Cart, and a home interface called CartHome.
When you use JBuilder’s EJB wizards, the home and remote/local
interfaces are created at the same time the bean class is. If you already
have an EJB 1.1 session bean, but not the interfaces, use the EJB 1.x
Interfaces wizard to create the interfaces. To use the wizard, display the
source code of the your enterprise bean in the code editor and choose
Wizards|EJB|EJB 1.1 Interfaces. Respond to the wizard’s prompts and
when you are done, the wizard creates a home and a remote interface for
your enterprise bean.
• getContents(), which gathers all the items in the shopping cart and
returns them in a lists that can be viewed or printed.
• purchaseItems(), which attempts to purchase the items.
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>cart</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>cart</ejb-name>
<method-name>purchase</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
The CartClient program is the client application that uses the Cart
enterprise bean. Its main() routine includes elements that all enterprise
bean client application must implement. It demonstrates how to
• Use JNDI to locate the bean’s home interface.
• Use the home interface’s create() method to create a new remote Cart
object.
• Invoke a method declared in the Cart object.
public static void main(String] args) throws Exception {
// get a JNDI context using the Naming service
javax.naming.Context context = new javax.naming.InitialContext();
Because the user is finished with the shopping session, the program
removes the cart. It’s not necessary to remove the cart, although it is good
programming practice to do so. A session bean exists for the client that
created it. When the client ends the session, the container automatically
removes the session bean object. The container also removes the session
bean object when it times out, although this doesn’t happen immediately.
CartClient also includes code that extends the generic Item class with two
types of items: a book and a compact disc. Book and CompactDisc are the
classes used in the example.
Bean-managed persistence
An entity bean with bean-managed persistence contains the code to access
and update a database. That is, you, as the bean provider, write database
access calls directly in the entity bean or its associated classes. Usually you
write these calls using JDBC.
The database access calls can appear in the entity bean’s business
methods, or in one of the entity bean interface methods. (You’ll read more
about the entity bean interface soon.)
Usually a bean with bean-managed persistence is more difficult to write
because you must write the additional data-access code. And, because you
might choose to embed the data-access code in the bean’s methods, it can
also be more difficult to adapt the entity bean to different databases or to a
different schema.
Container-managed persistence
You don’t have to write code that accesses and updates databases for
entity beans with container-managed persistence. Instead, the bean relies
on the container to access and update the database.
Container-managed persistence has many advantages compared to
bean-managed persistence:
• Such beans are easier to code.
• Persistence details can be changed without modifying and recompiling
the entity bean. Instead the deployer or application assembler can
modify the deployment descriptor.
• The complexity of the code is reduced, as is the possibility of errors.
• You, as the bean provider, can focus on the business logic of the bean
and not on the underlying system issues.
Container-managed persistence has some limitations, however. For
example, the container might load the entire state of the entity object into
the bean instance’s fields before it calls the ejbLoad() method. This could
lead to performance problems if the bean has many fields.
modeling this employee table would also use the social security number
for its primary key.
For enterprise beans, the primary key is represented by a String or Integer
type or a Java class containing the unique data. This primary key class can
be any class as long as that class is a legal value type in RMI_IIOP. This
means the class must extend the java.io.Serializable interface, and it must
implement the Object.equals(Other other) and Object.hashCode() methods,
which all Java classes inherit.
The primary key class can be specific to a particular entity bean class. That
is, each entity bean can define its own primary key class. Or multiple
entity beans can share the same primary key class.
Method Description
setEntityContext() Sets an entity context. The container uses this method to
pass a reference to the EntityContext interface to the bean
instance. The EntityContext interface provides methods to
access properties of the runtime context for the entity bean.
An entity bean instance that uses this context must store it in
an instance variable.
unsetEntityContext() Frees the resources that were allocated during the
setEntityContext() method call. The container calls this
method before it terminates the life of the current instance of
the entity bean.
ejbRemove() Removes the database entry or entries associated with this
particular entity bean. The container calls this method when
a client invokes a remove() method.
ejbActivate Notifies an entity bean that it has been activated. The
container invokes this method on the instance selected from
the pool of available instances and assigned to a specific
entity object identity. When the bean instance is activated, it
has the opportunity to acquire additional resources that it
might need.
ejbPassivate() Notifies an entity bean that it is about to be deactivated—
that is, the instance’s association with an entity object
identity is about to be broken and the instance returned to
the pool of available instances. The instance can then release
any resources allocated with the ejbActivate() method that it
might not want to hold while in the pool.
Method Description
ejbLoad() Refreshes the data the entity object represents from the
database. The container calls this method on the entity bean
instance so that the instance synchronizes the entity state
cached in its instance variables to the entity state in the
database.
ejbStore() Stores the data the entity object represents in the database.
The container calls this method on the entity bean instance
so that the instance synchronizes the database state to the
entity state cached in its instance variables.
ejbCreate() method
If you choose to add additional ejbCreate() methods that include
parameters, remember these rules:
• Each ejbCreate() must be declared as public.
• For container-managed entity beans, an ejbCreate() method must
return null.
The container has complete responsibility for creating
container-managed entity beans.
• For bean-managed entity beans, an ejbCreate() method must return an
instance of the primary key class for the new entity object.
The container uses this primary key to create the actual entity reference.
ejbPostCreate() method
When an ejbCreate() method finishes executing, the container then calls a
matching ejbPostCreate() method to allow the instance to complete its
initialization. The ejbPostCreate() matches the ejbCreate() method in its
parameters, but it returns void:
public void ejbPostCreate( <zero or more parameters> )
// implementation
}
Follow these rules when defining an ejbPostCreate():
• It must be declared as public.
• It can’t be declared as final or static.
• Its return type must be void.
• Its parameter list must match that of the corresponding ejbCreate()
method.
Use ejbPostCreate() to perform any special processing your bean needs to
do before it becomes available to the client. If your bean doesn’t need to
do any special processing, leave the method body empty, but remember to
include one ejbPostCreate() for every ejbCreate() for an entity bean with
bean-managed persistence.
instance in the pool. The instance remains in the pooled state during the
execution of a finder method.
When the container selects an instance to service a client’s requests to an
entity object, that instance moves from the pooled to the ready state. There
are two ways that an entity instance moves from the pooled state to the
ready state:
• Through the ejbCreate() and ejbPostCreate() methods.
• Through the ejbActivate() method.
The container selects the instance to handle a client’s create() request on
the bean’s home interface. In response to the create() call, the container
creates an entity object and calls the ejbCreate() and ejbPostCreate()
methods when the instance is assigned to the entity object.
The container calls the ejbActivate() method to activate an instance so that
it can respond to an invocation on an existing entity object. Usually the
container calls ejbActivate() when there is no suitable instance in the
ready state to handle the client’s calls.
implement one. The create() method inserts a new entity bean object into
the underlying database. You could choose to defer the creation of new
entity objects to the DBMS or to another application, in which case you
would not define a create() method.
The create() method requires two parameters, an account name string and
a balance amount. The implementation of this method in the entity bean
class uses these two parameter values to initialize the entity object state—
the account name and the starting balance—when it creates a new object.
The throws clause of a create() method must include the
java.rmi.RemoteException and the java.ejb.CreateException. It can also
include additional application-specific exceptions.
Entity beans must have the findByPrimaryKey() method, so the AccountHome
interface declares this method. It takes one parameter, the AccountPK
primary key class, and returns a reference to the Account remote interface.
This method finds one particular account entity and returns a reference to
it.
Although it’s not required, the home interface also declares a second
finder method, findAccountsLargerThan(). This method returns a Java
Enumeration containing all the accounts whose balance is greater than some
amount.
First look at the ejbLoad() method, which accesses the database entity
object, to see how a bean with bean-managed persistence implements
database access. Note that all of the methods implemented in the
SavingsAccount class follow the same approach as ejbLoad() uses. The
ejbLoad() method begins by establishing a connection to the database. It
calls the internal getConnection() method, which uses a DataSource to obtain
a JDBC connection to the database from a JDBC connection pool. Once the
connection is established, ejbLoad() creates a PreparedStatement object and
builds its SQL database access statement. Because ejbLoad() reads the
entity object values into the entity bean’s instance variables, it builds an
SQL SELECT statement for a query that selects the balance value for the
savings account whose name matches a pattern. The method then
executes the query. If the query returns a result, it extracts the balance
amount. The ejbLoad() method finished by closing the PreparedStatement
objects and then closing the database connection. Note that the ejbLoad()
method doesn’t actually close the connection. Instead, it simply returns
the connection to the connection pool.
import.java.sql.*;
import javax.ejb.*;
import java.util.*;
import java.rmi.RemoteException;
try {
Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement
("INSERT INTO Savings_Accounts (name, balance) VALUES (?,?)*);
statement.setString(1, _name);
statement.setFloat(2, _balance);
if(statement.executeUpdate() != 1) {
throw new CreateException("Could not create: " + name);
}
statement.close();
connection.close();
return new AccountPK(name);
} catch(SQLException e) {
throw new RemoteException("Could not create: " + name, 3);
}
}
...
public void ejbRemote() throws RemoteException, RemoveException {
try {
Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement
("DELETE FROM Savings Account WHERE name = ?");
statement.setString(1, _name);
if(statement.executeUpdate() != 1) {
throw new RemoteException("Could not remove: " + _name, e);
}
statement.close();
connection.close();
} catch(SQLException e) {
throw new RemoteException("Could not remove: " + _name, e);
}
}
public AccountPK ejbFindByPrimaryKey(AccountPK key) throws RemoteException,
FinderException {
try {
Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement
("SELECT name FROM Savings_Accounts WHERE name = ?");
statement.setString(1, key.name);
ResultSet resultSet = statement.executeQuery();
if(!resultSet.next()) {
throw new FinderException("Could not find: " + key
statement.close();
connection.close();
return key;
} catch(SQLException e) {
throw new RemoteException("Could not find: " + key, e);
}
}
<ejb-name>checking</ejb-name>
<home>AccountHome></home>
<remote>Account</remote>
<ejb-class>chkingAccount</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>AccountPK>/prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>name</field-name>
<cmp-field>
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>chekcing</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute-transaction>
</container-transaction>
</assembly-descriptor>
Developing message-driven
Chapter15
15
beans
Message-driven beans, introduced in the EJB 2.0 specification, greatly
simplify message-based programming. The bean provider’s primary
responsibility is implementing an onMessage() method that contains the
logic that responds to a message. The EJB container handles all other
messaging tasks. Message-driven beans use a Java Message Service (JMS)
provider, such as SonicMQ Message Broker that is bundled with JBuilder
Enterprise.
A message-driven bean is an enterprise bean that processes (JMS)
messages. Such messages can come from any component that can send
JMS messages, such as another enterprise bean, an application client, a
web component, or a legacy system. A message-driven bean is a listener to
JMS messages, responding when it detects a particular type of message.
Much like stateless session beans, message-driven beans are not
associated with a single client and they do not have conversational state.
Message-driven beans listen and respond to asynchronous messages. When
a sender sends an asynchronous message, it does not wait for the receiver
of the message to receive and process the message before it continues with
its own work. In contrast, the sender of a synchronous message waits for
the receiver to process the message before program control returns to the
sender. Asynchronous messaging permits loose coupling between the
message sender (the message producer) and the message receiver (the
message consumer, the message-driven bean). This makes
message-driven beans particularly useful for business-to-business
interactions and integrating an EJB system with legacy systems.
EJB container calls the ejbRemove() method. The following diagram depicts
the life cycle of a message-driven bean instance:
In the source code of the bean class, find the onMessage() method and write
the logic that processes an incoming message as you see fit. You can add
other methods to the bean class that are invoked by the onMessage()
method.
You can use JBuilder’s Deployment Descriptor editor to edit the bean’s
deployment descriptor. Double-click the message-driven bean’s class
node in the project pane and click the DD Editor tab at the bottom of the
content pane. When the Deployment Descriptor editor appears, click its
Message Driven Bean tab to display the Message Driven Bean panel:
The next section explains some of the deployment attributes found on this
panel.
If you choose to begin your EJB development for 1.x beans by creating a
remote interface first, you can use the EJB 1.x Bean Generator to create a
skeleton bean class and the home interface. For more information about
using the EJB 1.x Bean Generator, see “Generating the bean class from a
remote interface” on page 6-12.
Each entity bean remote home or local home interface must define the
default finder method, findByPrimaryKey(). It allows a client to locate an
entity object using a primary key. This is findByPrimaryKey() for a home
interface:
<entity bean's remote interface> findByPrimaryKey(<primary key type> key)
throws java.rmi.RemoteException, FinderException;
This is findByPrimaryKey() for a local home interface:
<entity bean's local interface> findByPrimaryKey(<primary key type> key)
throws FinderException;
findByPrimaryKey() has a single argument, the primary key. Its return type
is the entity bean’s remote or local interface. In the bean’s deployment
descriptor, you tell the container the type of the primary key.
findByPrimaryKey() always returns a single entity object.
You can define additional finder methods in the remote home and/or
local home interface. Each finder method must have a corresponding
implementation in the entity bean class for bean-managed persistence. For
container-managed persistence, the container implements the finder
methods. Each finder method must follow these conventions:
• In a remote home interface, the return type is the remote interface type,
or for finder methods that return more than one entity object, a
collection type that has the remote interface type as the content type. In
a local home interface, the return type is the local interface type, or for
finder methods that return more than one entity object, a collection
type that has the local interface type as the content type. Valid Java
collection types are java.util.Enumeration and java.util.Collection.
• The finder method always starts with the prefix find. The
corresponding finder method in the entity bean class with
bean-managed persistence begins with the prefix ejbFind.
• The method must throw the exception java.rmi.RemoteException if it is
defined in a home interface. Finders in a local home interface must not
throw RemoteException.
• The method must throw the exception javax.ejb.FinderException.
• The throws clause of the finder method in the remote home/local home
interface must match the throws clause of the corresponding
ejbFind<xxx> method in the entity bean class.
The following sample home interface contains two create() methods and
two finder methods. The parts shown in bold are required:
public interface AccountHome extends javax.ejb.EJBHome {
Each method defined in the remote or local interface must follow these
rules, which are the same for both session and entity beans:
• It must be public.
• It must throw the exception java.rmi.RemoteException if its a method in a
remote interface. It must not throw RemoteException if its a method in a
local interface.
• A method must exist in the remote/local interface for each method in
the enterprise bean’s class you want a client to be able to call. The
methods in the remote/local interface and in the bean itself must have
the same name, the same number and types of arguments, the same
return type, and they must throw the same exceptions, or a subset of
the remote/local interface method’s exceptions.
The following code sample shows the code for a sample remote interface
called Atm for an ATM session bean. The Atm remote interface defines a
business method called transfer(). The parts shown in bold are required:
public interface Atm extends javax.ejb.EJBObject{
interface as well as all the business methods you define in the remote
interface. The instantiated EJBObject is visible over the network and it acts
as a proxy for the bean. It has a stub and a skeleton. The bean itself is not
visible over the network.
For completeness, here is the EJBLocalObject interface:
package javax.ejb;
public interface EJBLocalObject (
public EJBHome getEJBLocalHome() throws EJBException;
public Object getPrimaryKey() throws EJBException;
public void remove() throws RemoveException, EJBException,;
boolean isIdentical (EJBLocalObject other) throws EJBException;
}
Session beans
If the enterprise bean is a session bean, the client uses a create method to
return the remote interface. Session beans don’t have finder methods. If
the session bean is stateless, it will have just one create() method, so that is
the one the client must call to obtain the remote interface. The default
create() method has no parameters. So for the SortClient code sample, the
call to the get the remote interface looks like this:
Sort sort = home.create();
Entity beans
If it’s an entity bean, use either a create or a finder method to obtain the
remote interface. Because an entity object represents some underlying
data stored in a database, and that data is persistent, entity beans usually
exist for a long time. Therefore, the client most often needs to simply find
the entity bean that represents that data rather than create a new entity
object, which would create and store new data in the underlying database.
A client uses a find operation to locate an existing entity object, such as a
specific row within a relational database table. That is, find operations
locate data entities that have previously been inserted into data storage.
The data might have been added to the data store by an entity bean, or it
might have been added outside of the EJB context, such as directly from
within the database management system (DBMS). Or, in the case of legacy
systems, the data might have existed prior to the installation of the EJB
container.
A client uses an entity bean object’s create() method to create a new data
entity that will be stored in the underlying database. An entity bean’s
create() method inserts the entity state into the database, initializing the
entity’s variables according to the values in the create() method’s
parameters.
Each entity bean instance must have a primary key that uniquely
identifies it. An entity bean instance can also have secondary keys that can
be used to locate a particular entity object.
Calling methods
Once the client has a reference to the bean’s remote interface, it can invoke
the methods defined in the remote interface for the bean. The client is
most interested in the methods that embody the bean’s business logic.
For example, the following is some code from a client that accesses the cart
session bean. The code shown here begins from the point where it has
created a new session bean instance for a card holder and retried a Cart
reference to the remote interface. The client is ready to invoke the bean
methods:
...
Cart cart;
{
...
Managing transactions
A client program can manage its own transactions rather than letting the
enterprise bean (or container) manage the transactions. A client that
manages its own transactions does so in exactly the same manner as a
session bean that manages its own transactions.
When a client manages its own transactions, it’s responsible for delimiting
the transaction boundaries. That is, it must explicitly start the transaction
and end (commit or roll back) the transaction.
A client uses the javax.transaction.UserTransaction interface to manage its
own transactions. It must first obtain a reference to the UserTransaction
interface, using JNDI to do so. Once it has the UserTransaction context, the
client uses the UserTransaction.begin() method to start the transaction,
followed later by the UserTransaction.commit() method to commit and end
the transaction (or UserTransaction.rollback() to rollback and end the
transaction). In between, the client accesses EJB objects and so on.
The code shown here demonstrates how a client would manage its own
transactions; the code that pertains specifically to client-managed
transactions are highlighted in bold:
...
import javax.naming.InitialContext;
import javax.transaction.UserTransaction;
...
public class clientTransaction {
public static void main (String[] args) {
InitialContext initContext = new InitialContext();
UserTransaction ut = null;ut =
(UserTransaction)initContext.lookup("java:comp/UserTransaction");
// start a transaction
ut.begin();
18
Managing transactions
Chapter18
Characteristics of transactions
Usually transactions refer to operations that access a database. All access
to the database occurs in the context of a transaction. All transactions
share these characteristics, denoted by the acronym ACID:
• Atomicity
Usually a transaction consists of more than a single operation.
Atomicity requires that all of the operations of a transaction are
performed successfully for the transaction to be considered complete. If
all of a transaction’s operations can’t be performed, that none of them
are allowed to be performed.
• Consistency
Consistency refers to database consistency. A transaction must move
the database from one consistent state to another, and it must preserve
the database’s semantic and physical integrity.
• Isolation
Isolation requires that each transaction appear to be the only
transaction currently manipulating the data in the database. Although
other transactions can run concurrently, a transaction shouldn’t see
these manipulations until and unless they complete successfully and
commit their work. Because of interdependencies among updates, a
transaction might get an inconsistent view of the data were it to see just
a subset of another transaction’s updates. Isolation protects a
transaction from this sort of data inconsistency.
Isolation is related to transaction concurrency. There are levels of
isolation. Higher degrees of isolation limit the extent of concurrency.
The highest level of isolation occurs when all transactions can be
serialized. That is, the database contents appear as if each transaction
ran by itself to completion before the next transaction began. Some
applications, however, might be able to tolerate a reduced level of
isolation for a higher degree of concurrency. Usually these applications
run a greater number of concurrent transactions, even it transactions
are reading data that might be partially updated and possibly
inconsistent.
• Durability
Durability means that updates made by committed transactions persist
in the database regardless of failure conditions. Durability guarantees
that committed updates remain in the database despite failures that
occur after the commit operation, and that the databases can be
recovered after a system or media failure.
operation calls the transaction starting method, but no operation calls the
transaction ending method.
Whenever possible, you should write enterprise beans that use
container-managed transactions. They require less work on your part and
are less prone to errors. Also, it’s easier to customize a bean with a
container-managed transaction and to use it to compose other beans.
dataSource1 = (javax.sql.DataSource)
context.lookup("java:comp/env/jdbcDatabase1");
firstConnection = dataSource1.getConnection();
firstStatement = firstConnection.createStatement();
dataSource2 = (javax.sql.DataSource)
context.lookup("java:comp/env/jdbcDatabase2");
secondConnection = dataSource2.getConnection();
secondStatement = secondConnection.createStatement();
utx = ejbContext.getUserTransaction();
utx.begin();
firstStatement.executeQuery(...);
firstStatement.executeUpdate(...);
secondStatement.executeQuery(...);
secondStatement.executeUpdate(...);
utx.commit();
firstStatement.close;
secondStatement.close
firstConnection.close();
secondConnection.close();
}
...
System-level exceptions
An enterprise bean throws a system-level exception (usually a
java.ejb.EJBException, but possibly a java.rmi.RemoteException) to indicate
an unexpected system-level failure. For example, it throws an exception if
it can’t open a database connection. The java.ejb.EJBException is a runtime
exception and it isn’t required to be listed in the throws clause of the bean’s
business methods.
System-level exceptions usually require the transaction to be rolled back.
Often the container managing the bean does the rollback. Sometimes the
client must roll back the transaction, though, especially if transactions are
bean-managed.
Application-level exceptions
The bean throws an application-level exception to indicate
application-specific error conditions. These are business logic errors, not
system problems. Application-level exceptions are exceptions other than
java.ejb.EJBException. Application-level exceptions are checked
exceptions, which means you must check for them when you call a
method that potentially can throw this exception.
The bean’s business methods use application exceptions to report
abnormal application conditions, such as unacceptable input values or
amounts beyond acceptable limits. For example, a bean method that
debits an account balance might throw an application exception to report
that the account balance isn’t sufficient to permit a particular debit
operation. A client can often recover from these application-level errors
without having to roll back the entire transaction.
The application or calling program gets back the same exception that was
thrown, allowing the calling program to know the precise nature of the
problem. When an application-level exception occurs, the enterprise bean
instance doesn’t automatically roll back the client’s transaction. The client
now has the knowledge and the opportunity to evaluate the error
message, take the necessary steps to correct the situation, and recover the
transaction. Or the client can abort the transaction.
You, as the bean provider, must ensure that the state of the bean is such
that if the client continues with the transaction, there is no loss of data
integrity. If you can’t ensure this, you must mark the transaction for
rollback.
Transaction rollback
When your client gets an application exception, first check if the current
transaction has been marked for rollback only. For example, a client might
receive a javax.transaction.TransactionRolledbackException. This exception
indicates that the helper enterprise bean failed and the transaction has
been aborted or marked “rollback only”. Usually the client doesn’t know
the transaction context within which the enterprise bean operated. The
bean might have operated in its own transaction context separate from the
calling program’s transaction context, or it might have operated in the
calling program’s context.
If the enterprise bean operated in the same transaction context as the
calling program, then the bean itself (or its container) has already marked
the transaction for rollback. When an EJB container marks a transaction
for rollback, the client should stop all work on the transaction. Usually a
client using declarative transactions gets an appropriate exception, such as
javax.transaction.TransactionRolledbackException. Note that declarative
transactions are those transactions where the container manages the
transaction details.
A client that is itself an enterprise bean should call the
javax.ejbEJBContext.getRollbackOnly() method to determine if its own
transaction has been marked for rollback.
For bean-managed transactions, which are those transactions managed
explicitly by the client, the client should roll back the transaction by
calling the rollback() method from the java.transaction.userTransaction
interface.
2 Specify the package and class name for your class or accept the default
values.
3 Enter the class you want this class to extend or accept the default value
of java.lang.Object in the Super Class field.
4 Select Publish And Subscribe if you are creating a class for a publish\
subscribe message system, or select Point To Point if you are creating a
class for a point to point message system.
5 Choose Next.
The next page that appears in the JMS message depends on the Domain
type you selected.
6 Leave the Generate Header Comments check box if you want the
comments listing the title, description, and so on included in the
generated code.
7 Choose Finish.
The commented code at the top of the generated class file demonstrates
how to send a text message and also how to receive a message. Follow this
example and add the code you need to send or receive messages. If your
class is a message consumer, locate the onMessage() method in the source
code and complete its implementation so that it handles the received
message.
Index I-1
advantages 14-2 Data Source panel 11-26
editing Borland property settings 5-15 data source properties 11-28
limitations 14-2 displaying 5-32, 11-2
no primary key class 14-6 EJB Local References panel 11-20
container-managed transactions 18-3 EJB References panel 11-10
adding 11-23 Environment panel 11-9
containers Finders panel 11-35
EJB 3-5 General panel 11-5
See also EJB container Message Driven Bean panel 11-8
create methods method permissions 11-31
entity bean 14-5, 17-3 Properties panel 11-14
session bean 17-2 Resource Env Refs panel 11-21
create() Resource References panel 11-12
entity beans 16-5 Security Identity panel 11-18
exceptions 16-3, 16-5 Security Role References panel 11-13
session beans 16-3 security roles 11-30
CreateException exception 16-3, 16-5 server-specific Properties panel 11-22
creating transaction isolation levels 11-28
EJB 2.0 components 5-1 verifying descriptors 11-38
deployment descriptors
D application assembly information 10-5
changing bean information 11-4
data source properties container transactions 11-23
editing schema 5-15 creating 10-2, 11-1
data sources data source properties 11-28
EJB 11-26 data sources 11-26
exporting EJB 5-30 editing 11-1
importing into EJB Designer 5-13 EJB 1.1 persistence 11-34
modifying imported schema 5-15 EJB local references 11-20
properties 11-28 EJB references 11-10
transaction isolation levels 11-28 entity bean sample 14-20
database drivers environment properties 11-9
adding to project 4-7 finder methods 11-35
Database Schema Provider dialog box 5-13 information in 10-3
DataExpress for EJB components 12-1 inserting into EJB modules 8-1
deactivating message-driven bean properties 11-8
session bean instances 13-6 method permissions 11-31
default project properties 11-14
adding database drivers 4-7 purpose 10-2
deleting resource environment references 11-21
EJB instances 16-2 resource references 11-12
enterprise beans 16-8 security identity
Deploy Settings dialog box 10-1 EJB 11-18
deployed EJB JARS security roles 11-13, 11-30
listing 10-9 server-specific properties 11-22
deployer session bean 13-18
EJB role 3-4 structural information 10-4
deploying transaction isolation levels 11-28
EJB JAR to running container 10-9 transaction policies 11-23
EJB JARs 10-7 verifying 11-38
enterprise beans 10-1, 10-7 viewing 11-2
enterprise beans to WebLogic 10-1, 10-8 viewing EJB 2.0 source code 5-32
enterprise beans to WebSphere 10-1, 10-8 WebSphere 4.0 finder methods 11-37
Deployment Descriptor editor 11-1 XML file 8-4
CMP 1.1 panel 11-34 deployment EJB role 3-4
container transactions 11-23
Index I-3
business methods 14-7 home interface 14-10, 16-4
comparing two 16-8 local home interface 16-4
creating EJB 2.0 5-1 methods 14-5
creating with wizards 6-4 nonexistent state 14-8
deploying 10-1, 10-7 persistence 14-1
deploying to WebLogic servers 10-8 pooled state 14-8
deploying to WebSphere servers 10-8 primary keys 14-2, 17-3
deployment options 10-8 providing data from 12-1
developing with JBuilder 3-8 ready state 14-9
entity 3-7 referencing 17-3
errors in EJB Designer 5-31 referencing tables 5-19
generating from remote interface 6-12 remote interface 14-11
getting information 17-8 removing 14-1
hot deploying 10-9 resolving data to 12-1
how they work 3-6 sample 14-10, 14-11, 14-13
local and remote access 3-8 sharing home and remote interfaces 14-10
managing resources 13-3 states 14-8
message-driven 3-7, 15-1 writing 14-3
modifying 2.0 5-9 entity beans (2.0)
modifying attributes 5-9 adding finder methods 5-28
referencing tables 5-19 adding home methods 5-29
removing fields 5-10 creating 5-13
removing from EJB Designer 5-30 creating from imported data source 5-13
removing instances 16-8 creating relationships 5-23
removing methods 5-11 creating WebLogic 6.x relationships 5-26
running 9-5 editing properties 5-17
session 3-7 ejbHome() 5-29
test client 9-1 ejbSelect() 5-28
testing 9-5 removing relationships 5-27
testing remote methods 9-1 WebSphere 4.0 finder methods 11-37
transactions 18-3 EntityBean interface
types 3-7 entity bean implements 14-3
viewing source code 5-8 implementing 14-4
enterprise beans (2.0) methods 14-4
generating bean classes 5-17 environment properties
Enterprise JavaBean 1.x wizard 6-4 EJB 11-9
Enterprise JavaBeans 3-1 errors
architecture 3-4 in EJB Designer 5-31
developing 3-1 exceptions
roles 3-2 application transaction 18-7
specification 3-1 application-level 18-7
types 3-7 system-level transaction 18-7
why needed 3-1 transaction 18-6
Enterprise Setup menu command 4-1
EnterpriseBean interface F
extended by EntityBean 14-4
extended by SessionBean 13-2 field groups
entity bean classes WebLogic 6.1 5-22
requirements 14-3 fields
writing 14-3 adding and removing EJB 5-9
entity beans 3-7 findByPrimaryKey() 16-5, 17-3
create() 16-5, 17-3 findByPrimaryKeyLoadState property 11-14
data sources 11-26 finder methods 11-35, 14-5, 16-5, 17-2, 17-3
defined 14-1 adding to entity beans (2.0) 5-28
finder methods 11-35, 16-5, 17-3 creating 14-7
default 17-3
Index I-5
application server files 4-4 method-ready state
Borland AppServer 4.5 4-3 defined 13-6
Borland Enterprise Server 5.0 4-3 in transaction 13-8
WebLogic Server 5.1 4-3 methods
WebLogic Server 6.x 4-3 adding EJB 5-10
WebSphere 4.0 Single Server 4-3 removing EJB 5-11
WebSphere Server 4.0 Advanced Edition 4-3 middle tier 2-3
listing deployed JARS 10-9 technologies 2-6
local access multi-tier applications
enterprise beans 3-8 for distributed systems 3-1
local home interface 16-2 multi-tier architecture
creating 16-3 benefits 2-3
entity beans 16-4
finder methods 16-5 N
session beans 16-3
local interface naming context
creating 16-7 obtaining 17-2
EJBLocalObject 16-7 Never transaction attribute 11-23
LocalHome interface 16-2 newsgroups 1-5
locating Borland 1-5
enterprise beans with primary key 16-8 nonexistent state
lookup() 17-2 entity beans 14-8
NotSupported transaction attribute 11-23
M
O
Macintosh
support in JBuilder 1-3 online resources 1-4
Mandatory transaction attribute 11-23 onMessage() 15-2, 15-4
maxBeanInTransaction property 11-14 writing 15-4
maxBeansInCache property 11-14 operation EJB role 3-4
maxBeansInPool property 11-14 optimisticConcurrencyBehavior property 11-14
message consumers 15-1
Message Driven Bean panel 11-8 P
message models
parsing errors
point-to-point 15-2
in EJB Designer 5-31
subscribe-and-publish 15-2
passivation 13-6, 14-4
message producers 15-1
persistence 3-7
message selector 15-2, 15-6
1.1 entity beans 11-34
message systems
bean-managed 14-1, 14-2
point to point A-1
bean-managed disadvantages 14-2
publish/subscribe A-1
container-managed 14-1, 14-2
message-driven beans 3-7, 15-1
container-managed advantages 14-2
creating 5-12
container-managed disadvantages 14-2
creating with JBuilder 15-5
container-managed EJB 1.1 11-34
deployment descriptors 15-6
container-managed versus bean-managed 14-2
life cycle 15-2
entity beans 14-1
properties 11-8
persisting
writing 15-3
1.1 entity beans 11-34
MessageDrivenBean interface 15-4
point to point message model A-1, A-4
MessageListener interface 15-4
point-to-point messaging 15-2
messages
polled state
JMS A-1
entity beans return to 14-9
metadata
pooled state
defined 17-8
entity beans 14-8
method permissions 10-5, 11-31
Index I-7
EJB role 3-3
servers
T
EJB 3-5 Table Reference editor 5-19
running EJB 9-5 table references
server-specific EJB properties 11-22 entity beans 5-19
session bean classes target application server 4-1
requirements 13-2 technical support 1-4
Session Bean wrap Entity Bean design pattern 12-1 test clients
session beans 3-7, 13-1 creating EJB 9-1
Cart sample 13-11 declaring instance of 9-4
create methods 17-2 running EJB 9-5
create() 16-3 using EJB 9-4
creating 2.0 5-7 testing enterprise bean methods 9-1
creating with JBuilder 13-4 testing enterprise beans 9-5
home interface 16-3 topic connection factories A-3
implementing required methods 13-12 topic JMS destination 15-2
life cycle 13-6 topic subscription durability 15-6
local home interface 16-3 transacted sessions A-3
method-ready state 13-6 transaction
referencing 17-2 attributes 11-23
remove() 17-5 boundaries 17-7
sample 13-10 transaction isolation levels
SessionSynchronization interface 13-8 WebLogic 6.x 11-25
stateful 13-1, 17-2 transaction isolation policy
stateless 13-2, 17-2 WebLogic 6.x 11-25
stateless pool 13-6 transactionCommitMode property 11-14
types 13-1 transaction-ready state 13-9
writing 13-2 transactions
SessionBean interface and enterprise beans 18-3
extending 13-2 atomicity characteristic 18-1
methods 13-2 attributes 18-3
SessionContext interface 13-9 bean-managed 18-3
SessionSynchronization interface 5-7 boundaries 18-5
methods 13-9 characteristics 18-1
stateful session beans 13-8 concurrency characteristic 18-1
setEntityContext() 14-4 consistency 18-1
setRollbackOnly() 13-9 container-managed 11-23, 18-3, 18-4
setSessionContext() 13-3 demarcation 18-3, 18-5
sharing home and remote interfaces 14-10 durability characteristic 18-1
shopping cart exceptions 18-6
session bean sample 13-10 global 18-4
SmartAgent 4-4 isolation characteristic 18-1
SonicMQ Broker 15-7 isolation levels 11-28
source code local 18-4
viewing 2.0 deployment descriptors 5-32 managed by client 17-7
stateful beans policies 11-23
life cycle 13-6 rolling back 18-8
stateless beans WebLogic 6.x isolation policies 11-25
life cycle 13-6
stubs U
generating client 8-1
subscription durability 15-6 undeploying an EJB JAR 10-9
Supports transaction attribute 11-23 unsetEntityContext() 14-4
system administrator Use EJB Test Client wizard 9-4
EJB role 3-4 Usenet newsgroups 1-5
UserTransaction interface 17-7, 18-4, 18-5
Index I-9
I-10 Enterprise JavaBeans Developer’s Guide