As described in this book, the resulting Java Persistence APIreplaces container-managed persistence with a lighter-weight,Plain Old Java Object POJO persistence layer.. Chapter 2, Archit
Trang 1By Bill Burke, Richard Monson-Haefel
Publisher: O'Reilly Pub Date: May 16, 2006 Print ISBN-10: 0-596-00978-X Pages: 760
Table of Contents | Index
Trang 2By Bill Burke, Richard Monson-Haefel
Publisher: O'Reilly Pub Date: May 16, 2006 Print ISBN-10: 0-596-00978-X Pages: 760
Trang 8by Bill Burke and Richard Monson-Haefel
Copyright © 2006, 2004, 2001, 2000, 1999 O'Reilly Media, Inc.All rights reserved
Printed in the United States of America
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 for
most titles (safari.oreilly.com) For more information, contactour corporate/institutional sales department: (800) 998-9938 or
Trang 9Many 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
While every precaution has been taken in the preparation of this
Trang 10ISBN: 0-596-00978-X
[M]
Trang 12Enterprise JavaBeans™ is the core component technology of theJava Enterprise Edition platform It is an enterprise
infrastructure designed to provide developers with the
automatic management of many of the services essential toenterprise applications The EJB containerthe immediate
environment of enterprise bean components and the provider ofmanaged services to themis at the center of this architecture
However, to use this managed environment in earlier versions
of EJB, developers had to write to APIs that focused more onthe EJB container's requirements than on the business logic ofenterprise applications Consequently, EJB development wasunnecessarily complex For example:
Implementation of various EJB interfaces led to a lot of
boilerplate code for methods that were required by the
interface, but not needed by the application
An XML deployment descriptor was required to integrate theapplication with its environment and with container
services Access to the components' environment was
clumsy and nonintuitive
The design of container-managed persistence made domainobject modeling unnecessarily complex and heavyweight.While container-managed persistence was originally
conceived as an ease-of-use facility, in practice, it was
awkward and limiting
The purpose of the EJB 3.0 release was to refocus EJB on
simplifying the developer's tasksand to fix all of these problems,and more
Trang 13of complexity in the earlier EJB releases This involved
examining criticisms of EJB; understanding which EJB designpatterns were really antipatterns; identifying APIs that wereclumsy to use, were nonintuitive to newcomers to the
technology, or could be dispensed with entirely; and recognizingother aspects of the technology that were obstacles to ease ofuse
The preliminary list of what needed to be fixed together with aproposal for how the task could be approached formed the basis
of JSR 220, the Java Community Process specification requestwith which I launched EJB 3.0 Starting with the initial list of theAPIs that needed improvement, the EJB 3.0 Expert Group
undertook the process of brainstorming on better, simpler
constructs Bill Burke, the chief architect of the JBoss
application server and author of this book, was one of the keyparticipants in this effort
The Expert Group's work has resulted in a major simplificationand improvement All of the key EJB APIs are easier to use, andthe configuration-by-exception approach of EJB 3.0 allows
developers to rely on expected default behaviors The XML
deployment descriptor has become unnecessary, except for
addressing more advanced cases
The Java language metadata facility, newly added to Java SE,aided us in making these simplifications EJB 3.0 uses metadataannotations to express within Java code the dependencies ofEJB components upon container services, and thus to avoid theneed to provide a deployment descriptor Further, EJB 3.0
provides default values for metadata so that in general, thismetadata can be sparse
By using metadata annotations to designate environment
dependencies and life cycle callbacks, EJB 3.0 has also beenable to eliminate the requirement for the bean class to
implement to the EnterpriseBean interfaces A bean class can
Trang 14We were able to eliminate the earlier EJBHome factory patterns
as well by requiring smarter interpositioning on the part of thecontainer (transparently to the application) in creating
references to components and their instances at the time oflookup or injection Session beans can now be programmed asordinary Java classes with ordinary business interfaces, ratherthan as heavyweight components
These and other changes have greatly simplified the developerview Further, they leave the underlying EJB architecture
fundamentally unchanged, providing a migration path to EJB3.0
The simplification of container-managed persistence provided agreater challenge We began the effort here with the same
steps as the simplification of session beans and message-drivenbeans: elimination of unneeded interfaces, use of annotationsfor configuration information, and so on It soon became clear,however, that EJB persistence needed a more radical
transformation Further, the success of lighter-weight
object/relational mapping technologies such as Hibernate gaveclear guidance to the direction that this transformation shouldtake
As described in this book, the resulting Java Persistence APIreplaces container-managed persistence with a lighter-weight,Plain Old Java Object (POJO) persistence layer This layer
provides extensive support for domain object modeling,
including inheritance and polymorphism; numerous
enhancements to the EJB QL query language to provide richquery capabilities; and a specification for portable
object/relational mapping through use of annotations or an XMLdescriptor Persistent entities are now instances of ordinary (butmanaged) Java classes As such, they can be created with new
and passed to other application tiers as ordinary Java objects
Trang 15environments
Bill Burke's contributions to EJB 3.0 and the Java PersistenceAPI have been numerous and far reaching As chief architect forthe JBoss application server, he brought to the EJB 3.0 ExpertGroup key insights on container innovations, extensive
experience with the Hibernate object/relational persistence
technology, and a broad perspective on the needs of developersand their use of the EJB technology in real-world applications
In this new edition of Enterprise JavaBeans, based on the
earlier work by Richard Monson-Haefel, Bill Burke shares theseinsights together with his in-depth perspective on how thesenew, simplified EJB 3.0 APIs transform the enterprise Java
Trang 16Author's Note
In the spring of 2000, I left my CORBA development job at Ionaand went to a small startup that was building an e-marketingportal Coming from a CORBA background to an Enterprise
JavaBeans™ project was a bit alien to me I remember thinking,
"Why does the server side need a component model?" I quicklylearned that declarative transaction, security, and persistencemetadata played a crucial role in developing business
applications
Like many startups at that time, we ran into funding problems
at the end of 2000 We were about to go into beta with our firstcustomers when our problems were compounded when our
application server vendor revoked our demo license and
demanded payment We had to find a free solution fast, andthat was when I stumbled into the open source application
server, JBoss
It didn't take very long to convert to JBoss, but I found thatJBoss 2.0 was a bit raw in some areas I had an extensive
background in writing middleware under the tutelage of SteveVinoski at Iona, so it wasn't too difficult to jump into the
codebase I immediately began fixing bugs here and there,
submitting patches to the JBoss mail list After a few months ofcontributing, I received a strange email:
what do you do in real life
The email was from JBoss's founder, Marc Fleury Let me tellyou, JBoss was the first open source project I had ever
Trang 17message from Morpheus in the movie The Matrix I responded
to Marc's email, saying I worked for a struggling startup andthat I had written middleware at my previous job at Iona I got
a one-sentence response from Marc:
do you want to take the red pill
I was hooked I replied yes, and my journey down the rabbithole began I became a CVS committer and first worked on
entity bean synchronization Later that year, I helped SachaLabourey on JBoss's first clustering implementation The rest ishistory
Back in 2002, Richard Monson-Haefel, the original author of theEJB book series, contacted Marc about contributing a JBoss
workbook Marc wasn't interested, so he introduced Richard toSacha Labourey and me, and we wrote the workbook that
O'Reilly published with its book, Enterprise JavaBeans, Fourth
Edition When Richard retired from writing last year, I guess mywork was good enough that O'Reilly offered me the opportunity
to update the series to the latest EJB 3.0 specification
Who Should Read This Book
This book explains and demonstrates the fundamentals of theEJB 3.0 and Java Persistence programming models AlthoughEJB makes application development much simpler, it is still acomplex technology that requires a great deal of time and study
to master This book provides a straightforward, no-nonsenseexplanation of the underlying technology, Java™ classes andinterfaces, the component model, and the runtime behavior ofEJB It does not include material on previous versions of the
Trang 18Although this book focuses on the fundamentals, it's not a
"dummies" book EJB is an extremely complex and ambitiousenterprise technology While using EJB may be fairly simple, theamount of work required to understand and master EJB is
significant Before reading this book, you should be fluent in theJava language and have some practical experience developingbusiness solutions Experience with distributed object systems
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 4.0 Application Server
Part I: The EJB 3.0 Standard
Part 1 was adapted from Richard Monson-Haefel's fourth edition
of this book by yours truly, Bill Burke Linda DeMichiel, the EJB3.0 specification lead, wrote the foreword to this book Jason T.Greene adapted Chapters 18 and 19 Here is a summary of thecontent of the technical manuscript chapters:
Trang 19This chapter defines component transaction monitors andexplains how they form the underlying technology of theEJB component model
Chapter 2, Architectural Overview
This chapter defines the architecture of the EJB componentmodel and examines the differences between the threebasic types of enterprise beans: entity beans, session
Chapter 5, Persistence: EntityManager
This chapter explains how entity beans interact with thenew entity manager service
Trang 20This chapter defines the basic relational database mappingprovided by the Java Persistence specification
Chapter 7, Entity Relationships
This chapter picks up where Chapter 6 left off, expandingyour understanding of persistence and complex bean-to-bean relationships
Chapter 8, Entity Inheritance
This chapter discusses entity bean inheritance and how anobject hierarchy can be mapped to a relational database
events
Chapter 11, Session Beans
Trang 21This chapter shows how to develop stateless and statefulsession beans.
Trang 22Chapter 18, EJB 3.0: Web Services Standards
This chapter explains the XML, SOAP, WSLD, and UDDI webservices standards
Chapter 19, EJB 3.0 and Web Services
This chapter discusses how the JAX-RPC API supports webservices in EJB
Chapter 20, Java EE
This chapter provides an overview of Java EE 5 and explainshow EJB 3.0 fits into this new platform
Chapter 21, EJB Design in the Real World
This 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 shows how to execute examples from
those chapters in the book that include at least one significantexample You'll want to read the introduction to the workbook
to set up JBoss and configure it for the examples After that,
Trang 23you're reading For example, if you are reading Chapter 6 onmapping persistent objects, use the "Exercises for Chapter 6"chapter of the workbook to develop and run the examples onJBoss
Software and Versions
This book covers EJB 3.0 and Java Persistence 1.0 It uses Javalanguage features from the Java SE 5 platform, including JDBC.Because the focus of this book is on developing vendor-
independent EJB components and solutions, I have stayed awayfrom proprietary extensions and vendor-dependent idioms Youcan use any EJB-compliant server with this book, but you
should be familiar with your server's specific installation,
deployment, and runtime-management procedures to work withthe examples A workbook for the JBoss Application Server isincluded at the end of this book to help you get started
Trang 24to the TravelAgent EJB when we want to talk about the
enterprise bean in general and the Customer entity when wewant to talk about entity beans If we put the name in a
constant-width font, we are referring explicitly to the bean'sinterface or class; thus, TRavelAgentRemote is the remote interface
Trang 25Using Code Examples
This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books doesrequire permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from thisbook into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Enterprise JavaBeans 3.0, Fifth Edition, by Bill Burke
and Richard Monson-Haefel Copyright 2006 O'Reilly Media,Inc., 0-596-00978-X."
If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
Safari® Enabled
When you see a Safari® enabled icon on the cover ofyour favorite technology book, that means the book is availableonline through the O'Reilly Network Safari Bookshelf
Safari offers a solution that's better than e-books It's a virtual
Trang 26Comments and Questions
Please address comments and questions concerning this book tothe publisher:
http://www.oreilly.com/catalog/entjbeans5
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:
Trang 27Acknowledgments
Many individuals share the credit for this book's developmentand delivery Michael Loukides, the editor, and his team werepivotal to the success of every edition of this book Without histeam's experience, craft, and guidance, this book would nothave been possible I want to thank Jason T Greene for takingover the web services chapters I had no desire to learn JAX-WSbeyond the @WebService annotation Without the earlier work ofRichard Monson-Haefel, this book would not have been possible
It amazes me how the structure of this book could last five
editions, and it is a testament to Richard's writing capabilities Ialso want to thank Richard for passing the baton to me on thisseries It has been a great opportunity for me and for JBoss Inc
Many expert technical reviewers helped ensure that the
material was technically accurate and true to the spirit of EJBand Java Persistence Of special note are Emmanuel Bernard,who sits with Gavin King and me on the EJB 3.0 Expert Group
as JBoss's representatives, as well as John Mazzitelli, who wasthe only reviewer to read every single chapter Richard Monson-Haefel was also instrumental in providing feedback Other
Thanks also to Linda DeMichiel, the EJB 3.0 specification lead
Trang 28I want to thank my mother for staying up late at night to edit
my English papers in high school decades ago I haven't
forgotten, Mom! Finally, I want to thank my wife, Monica, forputting up with this grumpy old troll Her love and support areall I need in life
Trang 29Chapter 1: Introduction
Chapter 2: Architectural Overview
Chapter 3: Resource Management and Primary ServicesChapter 4: Developing Your First Beans
Trang 30Chapter 21: EJB Design in the Real World
Trang 31This book is about Enterprise JavaBeans 3.0, the latest version
of the Enterprise JavaBeans specification, and its counterpart,the new Java Persistence specification Just as the Java platformhas revolutionized the way we think about software
development, the Enterprise JavaBeans (EJB) and Java
Persistence specifications have revolutionized the way we thinkabout developing mission-critical enterprise software They
combine server-side components with distributed object
technologies, asynchronous messaging, web services, and
persistence to greatly simplify the task of application
development It automatically takes into account many of therequirements of business systems, including security, resourcepooling, concurrency, and transactional integrity
This book shows you how to use Enterprise JavaBeans and JavaPersistence to develop scalable, portable business systems Butbefore we can start talking about EJB itself, we'll need a briefintroduction to the technologies addressed by EJB and Java
Persistence, such as component models, distributed objects,asynchronous messaging, and web services In Chapter 2, we'lllearn about the overall architecture that EJB and Persistenceprovide In Chapters 3 and 4, we'll look at how these APIs areintegrated together in a Java enterprise environment The rest
Trang 32independence Since it was first released, Java has been
marketed 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-
a particular database implementation; just change JDBC
drivers, and you change databases.[*] It's the same with EJBand Java Persistence Ideally, an EJB component (an enterprisebean) or a Java Persistence object (an entity bean) can run inany application server that implements these specifications.[ ]
This means that you can develop and deploy your EJB businesssystem in one server, such as BEA's WebLogic, and later move it
to a different EJB server, such as Pramati, Sybase's EAServer, orIBM's WebSphere, or to an open source project such as JBoss,Apache Geronimo, or JOnAS Implementation independencemeans that your business components do not depend on thebrand of server, which gives you many more options before,during, and after development and deployment
[*] In some cases, differences in a database vendor's support for SQL may require customization of SQL
statements used in development.
[ ] Provided that the bean components and EJB servers comply with the specification, and no proprietary
functionality is used in development.
Trang 33Object-oriented languages such as Java, C++, C#, Python, andRuby are used to write software that is flexible, extensible, andreusablethe three axioms of object-oriented development Inbusiness systems, object-oriented languages are used to
improve development of GUIs, to simplify access to data, and toencapsulate 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 middle-tier application servers, which manage the
components 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
A Java servlet, for example, is a server-side component thatgenerates HTML and XML data for the presentation layer of aweb application (Struts and JSF components are also examples
of this type of server-side component) EJB message-drivenbeans, discussed later in this book, are server-side componentsthat can be used to consume and process asynchronous
messages
Trang 34component 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 Eachcomponent is like a Lego™ block that can be combined withother 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
1.1.1 Enterprise JavaBeans Defined
Sun Microsystems' definition of the Enterprise JavaBeans
architecture is as follows:
The Enterprise JavaBeans architecture is a component
Trang 35This means the EJB specification offers a standard model forbuilding server-side components that represent business
processes (purchasing, inventory, 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 TravelAgent componentcan "live" near the reservation database, or a Purchase
business-process component can live near the user interface.You can do whatever's necessary to minimize latency, share theprocessing load, or maximize reliability
Trang 36
Persistence is a higher-level abstraction above JDBC The
persistence layer maps objects to database storage so that theycan be queried, loaded, updated, or removed without having to
go through a verbose API such as JDBC In older versions ofEJB, persistence was part of the EJB platform Starting with EJB3.0, persistence has been spun off to its own specification,
called the Java Persistence API
The Java Persistence API defines a way to map regular, plain old
Java objects (sometimes referred to as POJOs) to a database.These plain Java objects are called entity beans Entity beansare like any other Java class, except that they have been
mapped, using Java Persistence metadata, to a database
Therefore, they may be inserted and loaded from a databasewithout the developer writing any JDBC connection code or
reading from result sets The Java Persistence API also defines aquery language that has features that parallel those in SQL, but
is tailored to work with Java objects rather than a raw relationalschema
In the EJB 2.1 specification, entity beans were very
"heavyweight" and dependent on the application server and theentire Java EE runtime environment In Java Persistence, entitybeans are regular Java objects that are managed by a
persistence service Unlike their EJB 2.1 counterparts, entities
in Java Persistence are not required to implement any specialspec-defined interfaces or classes Another weakness of the
older specification was that it left individual vendors to decidehow an object should be mapped to a particular database
representation This made EJB 2.1 entity beans mostly
nonportable between vendors The new Java Persistence
specification defines a complete object to relational mapping(ORM) so that entity beans can be ported easily from vendor tovendor Furthermore, because entity beans are now plain Java
Trang 37application server and can even be used to transfer data
between a client and a server This makes designs simpler andmore compact
Trang 38
In addition to supporting RMI-based distributed business
objects, Enterprise JavaBeans supports asynchronous
messaging An asynchronous messaging system allows two ormore applications to exchange information in the form of
messages A message, in this case, is a self-contained package
of business data and network routing headers The businessdata contained in a message can be anythingdepending on thebusiness scenarioand usually contains information about somebusiness transaction In enterprise systems, messages inform
an application of some event or occurrence in another system
Asynchronous messages may be transmitted from one
application to another on a network using message-orientedmiddleware (MOM) MOM products ensure that messages areproperly distributed among applications In addition, MOM
usually provides fault-tolerance, load-balancing, scalability, andtransactional support for enterprises that need to reliably
message In this way, the applications that receive messagesand those that send messages are decoupled Senders and
receivers are not bound to each other in any way and may sendand receive messages as they see fit
Trang 39so that it supports both RMI and asynchronous messaging EJB3.0 supports asynchronous messaging through the Java
(JMS) possible
JMS is a vendor-agnostic Java API that can be used with manydifferent MOM vendors JMS is very similar to JDBC in that anapplication developer can reuse the same API to access manydifferent systems If a vendor provides a compliant service
provider for JMS, the JMS API can be used to send messages toand receive messages from that vendor For example, you canuse the same JMS API to send messages with Progress's
Trang 40
driven bean types to support all kinds of protocols, includingSMTP for email, SNMP for device control, peer-to-peer protocols(e.g., BEEP and Jabber), and many other open and proprietarymessaging systems In addition, the message-driven bean hasbecome an elegant option for serving connections to legacytransaction processing systems like CICS, IMS, openUTM, andothers
The expansion of message-driven beans in EJB 2.1 to otherprotocols was made possible by the new Java EE ConnectorArchitecture (JCA 1.5), which defines a portable programmingmodel for interfacing with enterprise information systems Theuse of JCA in Java EE is analogous to the use of USB in
computer hardware A computer that supports USB can
interface with just about any USB-compliant device Similarly,
an EJB 3.0 container that supports JCA 1.5 can interface withany JCA 1.5-compliant resource For example, if Vendor XYZcreates a new message-driven bean component for its