Today, the focus has broadened considerably: Java has beenrecognized as an excellent platform for creating enterprise solutions, specifically for developing distributed server-side appli
Trang 1practical examples; adept coverage the key concepts EJBs ; and diagrams to illustrate the concepts presented The fourth edition also
Trang 2includes everything you need to get up to speed quickly on the changes in EJB version 2.1 as well as a JBoss implementation guide.
Trang 8Section A.5 Examine and Run the Client Applications
Colophon
Index
Trang 9The JBoss Workbook section of the book was previously
published as JBoss 3.2 Workbook for Enterprise JavaBeans,Third Edition
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available formost titles (http://safari.oreilly.com) For more information,contact our corporate/institutional sales department: (800)
998-9938 or corporate@oreilly.com
Nutshell Handbook, the Nutshell Handbook logo, and the
O'Reilly logo are registered trademarks of O'Reilly Media, Inc.Enterprise JavaBeans?, Fourth Edition, the image of a wallabyand joey, and related trade dress are trademarks of O'ReillyMedia, Inc
by JBoss, Inc in the United States and other countries
Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and O'Reilly Media, Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps
Trang 10While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein.
Trang 11Author's Note
What Is Enterprise JavaBeans?Who Should Read This Book?Organization
Software and Versions
Conventions
Comments and Questions
Acknowledgments
Trang 12In the winter of 1997, I was consulting on an e-commerce
project that was using Java RMI Not surprisingly, the projectfailed because Java RMI didn't address performance, scalability,failover, security, or transactions, all of which are vital in a
production environment Although the outcome of that project
is not unique to Java RMII have seen the same thing happenwith CORBAthe timing of the project was especially interesting
topic for the third installment of "The Cutting Edge" when I
discovered the first public draft of Enterprise JavaBeans, Version0.8 I had originally heard about this technology in 1996, butthis was the first time that public documentation had been
made available Having worked on CORBA, Java RMI, and otherdistributed object technologies, I knew a good thing when I saw
it and immediately began writing an article about this new
technology
That seems like eons ago Since I published that article in
March 1998, literally thousands of articles on EJB have beenwritten, and several books on the subject have come and gone.This book, now in its fourth edition, has kept pace with four
versions of the EJB specification in last five years As the
newest version of the specification takes flight, and a slew ofnew books on the subject debut, I can't help but remember thedays when the words "Enterprise JavaBeans" drew blank looks
Trang 13from just about everyone I'm glad those days are over.
Trang 14Today, the focus has broadened considerably: Java has beenrecognized as an excellent platform for creating enterprise
solutions, specifically for developing distributed server-side
applications This shift has much to do with Java's emergingrole as a universal language for producing implementation-
independent abstractions for common enterprise technologies.The JDBC™ API is the first and most familiar example JDBC(Java Database Connectivity) provides a vendor-independentJava interface for accessing SQL relational databases This
abstraction has been so successful that it's difficult to find a
relational database vendor that doesn't support JDBC Java
abstractions for enterprise technologies have expanded
considerably to include JNDI for abstracting directory services,JTA (Java Transaction API) for abstracting access to transactionmanagers, JMS (Java Message Service) for abstracting access todifferent message-oriented middleware products, and more
Enterprise JavaBeans, first introduced as a draft specification inlate 1997, has since established itself as one of the most
Trang 15transaction monitors provide a robust, component-based
environment that simplifies distributed development while
automatically managing the most complex aspects of enterprisecomputing, such as object brokering, transaction management,security, persistence, and concurrency
Enterprise JavaBeans defines a server-side component modelthat allows business objects to be developed and moved fromone brand of EJB container to another A component (i.e., anenterprise bean) presents a programming model that allows thedeveloper to focus on its business purpose An EJB server isresponsible for making the component a distributed object andfor managing services such as transactions, persistence,
concurrency, and security In addition to defining the bean'sbusiness logic, the developer defines the bean's runtime
attributes in a way that is similar to choosing the display
properties of visual widgets The transactional, persistence, andsecurity behaviors of a component can be defined by choosingfrom a list of properties The end result is that EJB makes
developing distributed-component systems that are managed in
a robust transactional environment much easier For developersand corporate IT shops that have struggled with the
complexities of delivering mission-critical, high-performancedistributed systems using CORBA, DCOM, or Java RMI, EJB
provides a far simpler and more productive platform on which
to base development efforts
When Enterprise JavaBeans 1.0 was finalized in 1998, it quicklybecame a de facto industry standard Many vendors announcedtheir support even before the specification was finalized Sincethat time, EJB has been enhanced three times The specificationwas updated in 1999, to Version 1.1, and again in 2001, to
Version 2.0, which was covered in the second and third editions
of this book The most recent revision to the specification,
Version 2.1, is covered by this, the fourth edition of Enterprise
JavaBeans This edition also covers EJB 2.0, which is for the
Trang 16Products that conform to the EJB standard have come from
every sector of the IT industry, including the TP monitor, CORBAORB, application server, relational database, object database,and web server industries Some of these products are based
on proprietary models that have been adapted to EJB; manymore wouldn't even exist without EJB
In short, Enterprise JavaBeans 2.1 and 2.0 provide a standarddistributed-component model that greatly simplifies the
development process and allows beans developed and deployed
on one vendor's EJB server to be easily deployed on a differentvendor's EJB server This book will provide you with the
foundation you need to develop vendor-independent EJB
solutions
Trang 17This book explains and demonstrates the fundamentals of theEnterprise JavaBeans 2.1 and 2.0 programming models
Although EJB makes distributed computing much simpler, it isstill a complex technology that requires a great deal of time andstudy to master This book provides a straightforward, no-
nonsense explanation of the underlying technology, Java classesand interfaces, component model, and runtime behavior of
compatible with EJB 2.0 and provides special notes and
Enterprise JavaBeans It includes material that is backward-chapters when there are significant differences between 2.1 and2.0
Although this book focuses on the fundamentals, it's not a
"dummies" book Enterprise JavaBeans is an extremely complexand ambitious enterprise technology While using EJB may befairly simple, the amount of work required to understand andmaster EJB is significant Before reading this book, you should
be fluent in the Java language and have some practical
experience developing business solutions Experience with
distributed object systems is not a must, but you will need
some experience with JDBC (or at least an understanding of thebasics) to follow the examples in this book If you are unfamiliar
Trang 18This book is organized into two parts: the technical manuscriptfollowed by the JBoss workbook The technical manuscript
explains what EJB is, how it works, and when to use it The
JBoss workbook provides step-by-step instructions for installing,configuring, and running the examples from the manuscript onthe JBoss 3.0 Application Server
Part I: The Technical Manuscript
The technical manuscript is covered in Chapters 1-19 and isabout 90% of the content for this book Chapter 1-Chapter 18
Chapter 2
This chapter defines the architecture of the Enterprise
JavaBeans component model and examines the differencebetween the three basic types of enterprise beans: entitybeans, session beans, and message-driven beans
Trang 19This chapter explains in detail how enterprise beans areaccessed and used by remote, local, and web service clientapplications
Chapter 6
This chapter provides an explanation of how to developbasic container-managed entity beans
Chapter 7
This chapter picks up where Chapter 6 left off, expandingyour understanding of container-managed persistence tocomplex bean-to-bean relationships
Chapter 8
Trang 20Chapter 9
This chapter covers the development of bean-managedpersistence beans including when to store, load, and
remove data from the database
Chapter 10
This chapter covers the general protocol between an entitybean and its container at runtime and applies to both
container-managed persistence and bean-managed
persistence
Chapter 11
This chapter shows how to develop stateless and statefulsession beans
Chapter 12
This chapter shows how to develop message-driven beans
in EJB 2.1 and 2.0
Chapter 13
Trang 21Chapter 14
This chapter explains Web services standards, XML, SOAP,WSLD, and UDDI
Chapter 15
This chapter discusses how Web services are supported inEJB using the JAX-RPC API
Chapter 18
This chapter provides an in-depth explanation of the XMLdeployment descriptors used in EJB 2.0 and 2.1
Trang 22This chapter provides some basic design strategies that cansimplify your EJB development efforts and make your EJBsystem more efficient
Part II: The JBoss Workbook
The JBoss workbook is an update of the JBoss workbook thatwas published as a supplement to the third edition of this book.The JBoss workbook shows how to execute the examples fromthis book on the JBoss 4.0 Application Server It's indispensible
to readers who want to code while learning and see the
examples from the book run on a real application server
The previous edition of this book published the JBoss Workbook
as a separate title along with three other workbooks for J2EE1.3 SDK, IBM WebSphere and BEA WebLogic All of the
workbooks were critical successes and popular with readers, butthey were not a very big commercial successyou could
download them for freeand were difficult to manage For thisedition, we decided to develop one workbook to reduce
expenses We also decided to bind it with the rest of the book tomake your life easieryou don't have to buy it separately or
download it off the Web
The JBoss workbook is really excellent and I'm proud to include
it in this book It was written by Bill Burke and Sacha Labourey,two of the people behind JBoss and acknowledged experts intheir fields That said, I want to make it clear to readers thatI'm not endorsing JBoss over other J2EE application servers.The JBoss workbook is included in this edition for pragmatic
reasons:
JBoss supported most, if not all, EJB 2.1 features when this
Trang 23other vendors did not
Bill Burke and Sacha Labourey were willing to commit thetime and effort to update their workbook and have it readyfor in time for printing They are also willing to keep it
updated as new JBoss versions come out
JBoss is free, and in a time when application servers costtens, if not hundreds of thousands of dollars to deploy, it's abetter choice for developers who are learning how to
develop EJB for the first time
The JBoss workbook shows how to execute examples from most
of the chapters in this bookbasically any chapter with at leastone significant example is covered by the workbook You'll want
to read the introduction to the workbook to set up JBoss andconfigure it for the examples After that, just go to the
workbook chapter that matches the chapter you're reading Forexample, if you are reading Chapter 6 on basic container-
managed persistence, use the "Chapter 6 Exercises" section ofthe workbook to develop and run the examples on JBoss
Trang 24This book covers Enterprise JavaBeans Versions 2.1 and 2.0 Ituses Java language features from the Java 1.2 platform
including JDBC Because the focus of this book is on developingvendor-independent Enterprise JavaBeans components and
solutions, I have stayed away from proprietary extensions andvendor-dependent idioms Any EJB-compliant server can beused with this book, but you should be familiar with your
Trang 25Used for emphasis in some code examples
Constant width italic
Used to indicate text that is replaceable For example, inBeanNamePK, you would replace BeanName with a specificbean name
Indicates a tip, suggestion, or general note.
Trang 26An Enterprise JavaBean consists of many parts; it's not a singleobject, but a collection of objects and interfaces To refer to anenterprise bean as a whole, we use its business name in Romantype, followed by the acronym EJB For example, we will refer
to the Customer EJB when we want to talk about the enterprisebean in general If we put the name in a constant-width font,
we are referring explicitly to the bean's remote interface; thus,CustomerRemote is the remote interface that defines the
business methods of the Customer EJB
Trang 27Please address comments and questions concerning this book tothe publisher:
http://www.oreilly.com/catalog/entjbeans4/
To comment on or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about books, conferences, software,
Resource Centers, and the O'Reilly Network, see the O'Reillyweb site at:
http://www.oreilly.com
The author maintains a web site for the discussion of EJB andrelated distributed computing technologies at
http://www.jmiddleware.com jMiddleware.com provides newsabout this book as well as code tips, articles, and an extensivelist of links to EJB resources
Trang 28The credit for this book's development and delivery is shared bymany individuals Michael Loukides, my editor, was pivotal tothe success of every edition of this book Without his
experience, craft, and guidance, this book would not have beenpossible I'm also greatful to the co-authors who contributedgreatly to the success of this fourth edition The JBoss
workbook was written by Bill Burke and Sacha Labourey It's asignificant contribution and I'm proud to have their names onthe cover of this book Keyton Weissenger and Shy Abermancollaborated to produce Chapter 19, which is an excellent
overview of real-world EJB design and performance issuesthatchapter is based on hard-earned experience deploying severalEJB production systems
Many expert technical reviewers helped ensure that the
material was technically accurate and true to the spirit of
Enterprise JavaBeans Of special note are Lance Anderson, BillBurke, Dave Cronin, James Pinpin, Tom Mars, and Ricky Yim.They contributed greatly to the technical accuracy of this bookand brought a combination of industry and real-world
experience to bear, helping to make this one of the best books
on Enterprise JavaBeans published today
I would also like to thank the folks at TheServerSide.com andeveryone in the community who provided valuable feedback,including (in alphabetical order) Michael Boyd, Ravi Brewster,Patrick De Clercq, Peter Durcansky, Sudheer Fernades, VickFisher, Thomas Foersch, John Guthrie, George Jiang, MarkusKnauss, Madhusudhan Konda, Ravi Kyamala, Lee Yeow Leong,David McCann, Olav Nybo, Sunil Patil, Zheng Ping, Manfred
Rosenboom, Viviane Costa Silva, Simon Spruzen, Bob Stine,Dave Tuke, Ray Yan, Chunshui Yu, and Ping Zheng
Special thanks also go to Greg Nyberg, Hemant Khandelwal,
Trang 29White, Evan Ireland, David Chappell (the NET guy), Jim Farley,Prasad Muppirala, Sriram Srinivasan, Anne Thomas, Ian
McCallion, Tim Rohaly, James D Frentress, Andrzej Jan
Taramina, Marc Loy, Don Weiss, Mike Slinn, and Kevin Dick Thecontributions of these technical experts were critical to the
technical and conceptual accuracy of earlier editions of this
book Others I would like to thank include Maggie Mezquita,Greg Hartzel, John Klug, and Jon Jamsa of BORN Information,all of whom suffered though the first draft of the first edition solong ago to provide valuable feedback
Thanks also to Vlad Matena and Mark Hapner of Sun
Microsystems, the primary architects of Enterprise JavaBeans;Linda DeMichiel, EJB 2.1/2.0 specification lead; and all the otherEJB 2.1 expert group members
Finally, I extend the most sincere gratitude to my wife, Hollie,for supporting and assisting me through the five years of
painstaking research and writing that were required to producefour editions of this book Without her unfailing support andlove, this book would not have been completed
Trang 30Chapter 1: Introduction
Chapter 2: Architectural Overview
Chapter 3: Resource Management and the PrimaryServices
Chapter 4: Developing Your First Enterprise BeansChapter 5: The Remote and Local Client View
Trang 31Chapter 19: EJB Design in the Real World
Trang 32developing mission-critical enterprise software It combines
server-side components with distributed object technologies,asynchronous messaging, and web services to greatly simplifythe task of application development It automatically takes intoaccount many of the requirements of business systems,
including security, resource pooling, persistence, concurrency,and transactional integrity
This book shows you how to use Enterprise JavaBeans to
develop scalable, portable business systems But before we canstart talking about EJB itself, we'll need a brief introduction tothe technologies addressed by EJB, such as component models,distributed objects, asynchronous messaging, and web services.It's particularly important to have a basic understanding of
component transaction monitors, the technology that lies
beneath EJB In Chapter 2 and Chapter 3, we'll look at EJB itselfand see how enterprise beans are put together The rest of thebook is devoted to developing enterprise beans for an imaginarybusiness and discussing advanced issues
It is assumed that you're already familiar with Java; if you're
not, Learning Java, by Patrick Niemeyer and Josh Peck
(O'Reilly), is an excellent introduction This book also assumesthat you're conversant in the JDBC API, or at least in SQL If
you're not familiar with JDBC, see Database Programming with
JDBC and Java by George Reese (O'Reilly).
One of Java's most important features is platform
Trang 33marketed as "write once, run anywhere." While the hype hasgotten a little heavy-handed at times, code written with Sun'sJava programming language is remarkably platform-
independent Enterprise JavaBeans isn't just platform-independentit's also implementation-independent If you've
worked with JDBC, you know a little about what this means Notonly can the JDBC API run on a Windows machine or on a Unixmachine, it can also access relational databases of many
different vendors (DB2, Oracle, MySQL, SQLServer, etc.) by
using different JDBC drivers You don't have to code to a
particular database implementationjust change JDBC drivers,and you change databases.[1] It's the same with EJB Ideally, anEJB componentan enterprise beancan run in any applicationserver that implements the EJB specification.[2] This means thatyou can develop and deploy your EJB business system in oneserver, such as BEA's WebLogic, and later move it to a differentEJB server, such as Pramati, Sybase EAServer, IBM's
WebSphere, or an open source project such as Apache
Geronimo, OpenEJB, JOnAS, or JBoss Implementation
independence means that your business components are notdependent on the brand of server, which gives you many moreoptions before, during, and after development and deployment
[1] In some cases, differences in database vendor's support for SQL may require customization of SQL statements used in development.
[2] Provided that the bean components and EJB servers comply with the specification, and no
proprietary functionality is used in development.
Trang 34Object-oriented languages such as Java, C++, and C# are used
to write software that is flexible, extensible, and reusablethethree axioms of object-oriented development In business
systems, object-oriented languages are used to improve
development of GUIs, to simplify access to data, and to
encapsulate the business logic The encapsulation of businesslogic into business objects is a fairly recent focus in the
information-technology industry Business is fluid, which meansthat a business's products, processes, and objectives evolveover time If the software that models the business can be
encapsulated into business objects, it becomes flexible,
extensible, and reusable, and therefore evolves as the businessevolves
A server-side component model may define an architecture for
developing distributed business objects that combines the
accessibility of distributed object systems with the fluidity ofobjectified business logic Server-side component models areused on the middle-tier application servers, which manage thecomponents at runtime and make them available to remote
clients They provide a baseline of functionality that makes iteasy to develop distributed business objects and assemble theminto business solutions
Server-side components can also be used to model other
aspects of a business system, such as presentation and routing.The Java servlet, for example, is a server-side component that
is used to generate HTML and XML data for the presentationlayer of a three-tier architecture EJB 2.1 message-driven
beans, which are discussed later in this book, are server-sidecomponents that can be used to consume and process
asynchronous messages
Server-side components, like other components, can be bought
Trang 35component model Server-side component models often supportattribute-based programming, which allows the runtime
behavior of the component to be modified when it is deployed,without having to change the programming code in the
component Depending on the component model, the serveradministrator can declare a server-side component's
transactional, security, and even persistence behavior by settingthese attributes to specific values
As an organization's services, products, and operating
procedures evolve, server-side components can be
reassembled, modified, and extended so that the business
system reflects those changes Imagine a business system as acollection of server-side components that model concepts such
as customers, products, reservations, and warehouses Each
component is like a Lego(™) block that can be combined with
other components to build a business solution Products can bestored in the warehouse or delivered to a customer; a customercan make a reservation or purchase a product You can
assemble components, take them apart, use them in differentcombinations, and change their definitions A business systembased on server-side components is fluid because it is
objectified, and it is accessible because the components can bedistributed
Trang 36Applications written using the Enterprise JavaBeans
architecture are scalable, transactional, and multi-user
secure These applications may be written once, and thendeployed on any server platform that supports the
Enterprise JavaBeans is a standard server-side componentmodel for distributed business applications
side components that represent both business objects
This means the EJB offers a standard model for building server-(customers, items in inventory, and the like) and business
processes (purchasing, stocking, and so on) Once you havebuilt a set of components that fit the requirements of your
business, you can combine them to create business
applications On top of that, as "distributed" components, theydon't all have to reside on the same server Components canreside wherever it's most convenient: a Customer componentcan "live" near the Customer database, a Part component canlive near the inventory database, and a Purchase business-
process component can live near the user interface You can dowhatever's necessary for minimizing latency, sharing the
processing load, or maximizing reliability
Trang 37To understand EJB, you need to understand how distributedobjects work Distributed object systems are the foundation formodern three-tier architectures In a three-tier architecture, asshown in Figure 1-1, the presentation logic resides on the client(first tier), the business logic resides on the middle tier (secondtier), and other resources, such as the database, reside on thebackend (third tier)
Trang 38The business object resides on the middle tier It's an instance
of an object that models the state and business logic of somereal-world concept, such as a person, order, or account Everybusiness object class has matching stub and skeleton classesbuilt specifically for that type of business object For example, adistributed business object called Person would have matchingPerson_Stub and Person_Skeleton classes As shown in Figure1-2, the business object and skeleton reside on the middle tier,and the stub resides on the client
is connected via the network to the skeleton The stub acts asthe business object's surrogate on the client and is responsiblefor communicating requests from the client to the business
object through the skeleton Figure 1-2 illustrates the process
of communicating a method invocation from the client to theserver object and back The stub and the skeleton hide the
communication specifics of the RMI protocol from the client andthe implementation class, respectively
[4] The acronym "RMI" isn't specific to Java RMI This section uses the term RMI to describe
distributed object protocols in general Java RMI is the Java language version of a distributed
object protocol.
Figure 1-2 RMI loop
Trang 39as the business object, but the stub's methods do not containbusiness logic Instead, the business methods on the stub
implement whatever networking operations are required to
forward the request to the business object and receive the
results When a client invokes a business method on the stub,the request is communicated over the network by streaming thename of the method invoked, and the values passed in as
parameters, to the skeleton When the skeleton receives theincoming stream, it parses the stream to discover which method
is requested, then invokes the corresponding business method
on the business object Any value that is returned from the
method invoked on the business object is streamed back to thestub by the skeleton The stub then returns the value to theclient application as if it had processed the business logic
locally
Trang 40The term "component model" has many different
interpretations Enterprise JavaBeans specifies a server-side
component model Using a set of classes and interfaces fromthe javax.ejb package, developers can create, assemble, anddeploy components that conform to the EJB specification
The original JavaBeans is also a component model, but it's not aserver-side component model like EJB Other than sharing thename "JavaBeans," these two component models are
completely unrelated In the past, a lot of the literature referred
to EJB as an extension of the original JavaBeans, but this is amisrepresentation The two APIs serve very different purposes,and EJB does not extend or use the original JavaBeans
component model
JavaBeans is intended to be used for intraprocess purposes, while EJB is designed for interprocess components In other
words, the original JavaBeans was not intended for distributedcomponents JavaBeans can be used to solve a variety of
problems, but it is primarily used to build clients by assemblingvisual (GUI) and nonvisual widgets It's an excellent componentmodel, possibly the best one ever devised for intraprocess
development, but it's not a server-side component model EJB,
on the other hand, is explicitly designed to address issues
tier architecture
involved with managing distributed business objects in a three-Given that JavaBeans and Enterprise JavaBeans are completelydifferent, why are they both called component models? In thiscontext, a component model defines a set of contracts betweenthe component developer and the system that hosts the
component The contracts express how a component should bedeveloped and packaged Once a component is defined, it
becomes an independent piece of software that can be