Head First EJB™ by Kathy Sierra and Bert Bates Copyright © 2003 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or
[email protected]. Editor:
Mike Loukides
Cover Designer:
Edie Freedman
Interior Decorators: Kathy Sierra and Bert Bates Anthropomorphizer: Bert Bates Bean Wrangler:
Kathy Sierra
Printing History: October 2003: First Edition.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. O’Reilly Media, Inc. is independent of Sun Microsystems. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. In other words, if you use anything in Head First EJB™ to, say, run a nuclear power plant or air traffic control system, you’re on your own. And although some people have been able to pass the exam simply by placing this book under their pillow each night for three consecutive weeks, we generally don’t recommend it. Most people find it helpful to actually read the book or at least look at the pictures. ISBN-10: 0-596-00571-7 ISBN-13: 978-0-596-00571-9 [M]
[8/07]
Table of Contents (summary) Intro
xix
1
Welcome to EJB: an introduction
1
2
EJB Architecture: architectural overview
3
Exposing Yourself: the client view
111
4
Being a Session Bean: session bean lifecycle
173
5
Entities are Persistent: entity bean intro
259
6
Being an Entity Bean: bean/entity synchronization
295
7
When Beans Relate: entity bean relationships
373
8
Getting the Message: message-driven beans
437
9
The Atomic Age: EJB transactions
469
10
When Beans Go Bad: exceptions in EJB
525
11
Protect Your Secrets: security in EJB
569
12
The Joy of Deployment: a bean’s environment
599
A
Appendix A: Final Mock Exam
637
61
Table of Contents (the real thing)
i
Intro Your brain on EJB.
Here you are trying to learn something, while here your brain
is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more important things, like which wild animals to avoid and whether naked snowboarding is a bad idea.” So how do you trick your brain into thinking that your life depends on knowing EJB? Who is this book for?
xviii
We know what your brain is thinking
xix
Metacognition
xxi
Bend your brain into submission
xxiii
What you need for this book
xxiv
Passing the certification exam
xxvi
Technical reviewers
xxviii
Acknowledgements
xxix
ix
1
Welcome to EJB Enterprise JavaBeans are easy. Well, at least when you compare EJB to what you’d have to do to write your own scalable, transactional, secure, persistent, concurrent enterprise component server. In this chapter, we’ll develop, deploy, and run an EJB application, and then dive into the details. Before we’re done, we’ll look at the use, benefits, and characteristics of EJB, and we’ll look (briefly) at how EJB containers work.
t EJB obj e c
En
an
services
biz interface
Server
terp se be ri
EJB Container
biz logic separate from data DB
2
Exam objectives
2
What is EJB all about?
3
No more vendor lock-in!
5
How does it all work?
7
Behind the scenes...
8
Beans come in three flavors
11
The Advice Guy bean
15
Five things you do to build a bean
16
EJB Roles and Responsibilities
26
Tutorial
28
Coffee Cram
59
EJB Architecture EJB is about infrastructure. Your components are the building blocks. With EJB, you can build big applications. The kind of applications that could run everything from the Victoria’s Secret back-end to document-handling systems at CERN. But an architecture with this much flexibility, power, and scalability isn’t simple. It all begins with a distributed programming model...
(J2SE API)
Remote
(J2EE API)
no methods
no methods
(J2EE API)
EJBObject // several methods
YOU write this interface (the remote component interface)
BookCart addBook() removeBook() showBooksInCart() doCheckout()
EnterpriseBean
(J2EE API)
SessionBean // several methods
BookCartBean
YOU write this class addBook() removeBook() (the bean class) showBooksInCart() doCheckout() // other methods
x
Exam objectives
62
Making a Remote method call
64
What about arguments and return values?
67
The client calls business methods through the Remote interface
79
EJB uses RMI
81
The Remote object is not the bean, it’s the bean’s bodyguard
82
Architectural overview: Session beans
98
Architectural overview: Entity beans
99
Architectural overview: Creating a Stateful Session bean
100
Architectural overview: Creating a Stateless Session bean
101
Architectural overview: Message-driven beans
106
Organize your beans
108
3
Exposing Yourself You can’t keep your bean private. Clients need to see what you’ve got. (Except for message-driven beans, which don’t have a client view). The Advice Bean exposes the getAdvice() method in its Component interface—the place where you declare business methods. But that’s not all the client sees. Remember, the Advice interface extends EJBObject, an interface with methods of its own. Methods the client can see. Methods the client can call. And it works the same way with the Home interface.
Stateless beans
These beans are all identical
bean
bean bean
For stateless session beans from the same home, isIdentical() always returns true, even for different beans.
4
Exam objectives
112
What the client really wants
113
What’s JNDI?
116
PortableRemoteObject.narrow() (exotic casting)
121
Writing the Remote home interface for a session bean
125
Thankfully, we’ve got handles (online shopping takes time)
139
Which methods make sense for the local client interfaces?
148
Why so many remove methods?
151
Comparing Remote vs. Local interfaces
154
Arguments to Remote vs. local methods
163
Coffee Cram
168
Being a Session Bean Session beans are created and removed. If you’re lucky, you’re a stateless bean. Because the life of a stateful bean is tied to the whims of a heartless client. Stateful beans are created at the client’s insistence, and live and die only to serve that one client. But ahhhh, the life of a stateless bean is fabulous! Pools, those little umbrella drinks, and no boredom since you get to meet so many different clients.
For me? This is such a special moment! Once in a lifetime...
Exam objectives
174
Container callbacks, for the special moments in a bean’s life
181
Bean Creation
188
Bean things you can do within business methods
199
Passivation: a stateful bean’s chance at scalability
200
Bean Removal
208
Writing a Session Bean: your job as Bean Provider
230
SessionContext: you need it more than it needs you
240
Coffee Cram
244
xi
5
Entities are Persistent Entity beans persist. Entity beans exist. Entity beans are. They are object representations of something in an underlying persistent store. (Think: database, because most entity beans represent something from a relational database.) If you have a Customer entity bean, then one bean might represent the entity Tyler Durden, ID #343,
If you’ve got any last words, you better do it in your ejbRemove()...
while another is the entity Donny Darko, ID #42. Three beans, representing three real entities. An entity bean is simply a realization of something that already exists.
No, Please, No! I’ll give you whatever you want, just don’t call remove()!
6 If I’m a bean I say to a method, “Don’t call me, call my bodyguard, and here’s his contact information...”
Instead of:
260
What’s an entity bean?
261
Entity beans from the client’s point of view
265
A very simple Customer entity bean
268
Entity bean Remote component interface
270
Entity bean Remote home interface
273
What does the client really want from an entity bean home?
274
Home business methods to the rescue
278
Session bean create() vs. entity bean create()
281
Session bean remove() vs. entity bean remove()
282
Entity/bean/instance death
285
Coffee Cram
288
Being an Entity Bean Entity beans are actors. As long as they’re alive, they’re either in the pool or they’re being somebody. Somebody from the underlying persistent store (an entity from the database). When a bean is playing a part, the bean and the underlying entity have to stay in sync. Imagine the horror if the bean is pretending to be, say, Audrey Leone, and someone lowers Audrey’s credit limit in the database... but forgets to tell the bean.
bean
doStuff(this); EJB object
Use: doStuff(myContext.getEJBObject());
xii
Exam objectives
Exam objectives
296
The real power of entity beans is synchronization
298
Container-managed vs. bean-managed persistence
303
The EntityBean interface adds new container callbacks
310
Writing a CMP entity bean
313
Object identity: the primary key
332
Finder methods
339
Home business methods
345
Coffee Cram
362
7
When Beans Relate Entity beans need relationships. An Order needs a Customer. A LineItem needs an Order. An Order needs LineItems. Entity beans can have container-managed relationships (CMR) and the Container takes care of virtually everything. Make a new LineItem that’s related to an Order? If you ask the Customer to show you his Orders, you’ll see the new LineItem. Best of all, you can use EJB-QL to write portable queries.
Multiplicity: many
Multiplicity: one Director
Movie
Collection getMovies()
Director getDirector()
0..*
1
one Director. Each Movie has y Movies. man A Director has
8 EJBContext
getCallerPrincipal() getEJBHome() isCallerInRole(String s) getRollbackOnly() getEJBLocalHome() getUserTransaction() setRollbackOnly()
MessageDrivenContext
Exam objectives
374
Relationships
378
Multiplicity
380
CMP and CMR fields
383
Cascade delete can propagate
393
EJB-QL for the MovieBean
402
SELECT and FROM are the mandatory!
409
The WHERE clause
411
Collections don’t bark()!
414
The BETWEEN, IN, IS EMPTY, and LIKE expression
416
Relationship assignments
421
Coffee cram
425
Getting the Message It’s fun to receive messages. Not as much fun as, say, getting that eBay package with the genuine Smurf™ lamp, but fun and efficient nonetheless. Imagine if you sent your order to eBay, and you couldn’t leave your house until the package was delivered. That’s what it’s like with Session and Entity beans. But with message-driven beans, the client can send a message and walk away.
My life is sad. I have no home, I have no clients... I can use my context ONLY for transactions... Oh well, at least I get a pool.
Exam objectives
438
Writing a message-driven bean: your job as Bean Provider
447
Complete DD for a message-driven bean
449
Topics and Queues
450
MessageDrivenContext
455
Message acknowledgement
458
Coffee Cram
463
// this interface adds no // new methods
xiii
9
The Atomic Age Transactions protect you. With transactions, you can try something knowing that if anything goes wrong along the way, you can just pretend the whole thing didn’t happen. Everything goes back to the way it was before. Transactions in EJB are a thing of beauty—you can deploy a bean with customized transaction behavior without touching the bean’s source code! But you can write transaction code, if you need to.
������������� CMT beans ru n transactions unknown, while BMT be ans use only their own. OK, not our be st work, we kn ow. So why don’t you tr y it. Memor y de vices can help, but they work much be tter when you create th em yourself.
10
Oh sh**! A system exception. Nothing I can do about it. There goes my stateful bean. I’ll have to start over...
Exam objectives
470
The ACID test
472
How it works in EJB
474
Transaction propagation
475
How do I make (or get) a transaction?
476
setRollbackOnly() lives in TWO interfaces
487
BMT can be a really BAD idea.
490
BMT hurts bean reuse
Container-managed transactions
491
How attributes work
492
Methods you MUST mark with an attribute (for a CMT bean)
498
“Unspecified Transaction Context”
499
DD example for CMT
503
SessionSynchronization “special moments”
512
Coffee cram
516
When Beans Go Bad Expect the unexpected. Despite your best efforts, things can go wrong. Terribly, tragically, wrong. You need to protect yourself. You can’t let your entire program collapse, just because one bean in the family throws an exception. The application must go on. You can’t prevent tragedy, but you can prepare for it. You need to know what is and is not recoverable, and who is responsible when a problem occurs.
Gotta love application exceptions... I can recover from this if I put in a different value for the argument to the create() method...
xiv
Exam objectives
526
In EJB, exceptions come in two flavors
532
With an Application Exception, the Container will...
533
With a System Exception, the Container will...
534
RemoteException vs. EJBException
539
Bean Provider’s responsibilities
541
The five standard EJB application exceptions
548
Common system exceptions
551
Coffee cram
563
11
Protect Your Secrets Keep your secrets. Security is about authentication and authorization. First, you have to prove your identity, and then we’ll tell you what you’re allowed to do. Security is easy in EJB, because you’re only dealing with authorization. You decide who gets to call which methods on your beans. Except one problem... if you’re a Bean Provider or App Assembler, you probably don’t know who the users are going to be! In a vendorspecific way
In the EJB Deployment Descriptor
<security-role-ref> <security-role> users and groups
In a companyspecific way
real people
Exam objectives
570
How to do security in EJB
573
The Application Assembler’s job: access control
574
Defining the method permissions
578
The Deployer’s job: mapping actual humans to abstract roles 583
12
Class-level vs. instance-level security
586
Using programmatic security to custom-tailor a method
587
Use security identity to pretend someone else is calling...
591
Security context propagation with
592
Coffee cram
593
The Joy of Deployment You worked hard on that bean. You coded, you compiled, you tested. About a hundred zillion times. The last thing you want to touch is already-tested source code, just because something simple changed in the deployment configuration. And what if you don’t even have the source code? EJB supports bean reuse through the customizable Deployment Descriptor and a bean’s special environment.
JAR 1
ejb-jar META-INF
com
UDQGRP@ `
$OYOUSEEANYTHINGINTHATMETHODTHATLOOKSSPECIlCTOA2EMOTECLIENT VIEW7OULDYOUNEEDTODOANYTHINGDIFFERENTWITHALOCALCLIENT .O DONTTHINKSO !NYTHINGTHATWORKSASARETURNTYPEORARGUMENTFORA2EMOTEMETHODIS GUARANTEEDTOWORKFORALOCALMETHODASWELL SOWERE/+THERE+IND OFANO BRAINERWHENTHERETURNTYPEIS3TRING THOUGH /+ THEREISONE EXCEPTIONREMEMBER ACCORDINGTO"EANLAWYOUMUSTNOTRETURNABEANS 2EMOTEINTERFACEFROMALOCALINTERFACEMETHOD 3OITLOOKSLIKEATLEASTWITHTHISBEAN WESHOULDNEVERHAVETOKNOWOR CARE7ESHOULDBEABLETODEPLOYTHEBEANASWRITTEN ANDTHEBEANSHOULD BEKEPTUNAWAREOFWHETHERITSCLIENTSARE2EMOTEORLOCAL 3OUNDSGOOD DOESNTIT3IMPLE CLEAN OBJECT ORIENTED "UTTHINKABOUTITSOMEMORE)MAGINEABEANWITHMORECOMPLEXLOGIC -OREBUSINESSMETHODS!RGUMENTSTOTHOSEMETHODS!RGUMENTSTHE METHODMIGHTEVENNEEDTOACTON (MMMMMCANYOUTHINKOFANYTHINGTHATTHEBEANMIGHTWANTTOTREAT DIFFERENTLY IFITKNEWTHECLIENTWERELOCALINSTEADOF2EMOTE
\RXDUHKHUH
SDVVLQJREMHFWVORFDOO\
:DLWDPLQXWH-DYD SDVVHVREMHFWVORFDOO\E\SDVVLQJ DFRS\RIWKHREMHFWUHIHUHQFHQRW WKHREMHFWLWVHOI%XWZHNQRZWKDW 5HPRWHPHWKRGDUJXPHQWVDQGUHWXUQ YDOXHVDUHSDVVHGDVD6HULDOL]HG FRS\RIWKHDFWXDOREMHFW
,QRUGLQDU\ORFDOPHWKRGFDOOV-DYDSDVVHV DQREMHFWUHIHUHQFHE\YDOXHDVDFRS\RIWKH UHIHUHQFHYDULDEOH 7KHREMHFWLWVHOILVQHYHUSDVVHG %XWZLWK5HPRWHFDOOVWKHREMHFWLWVHOILVFRSLHG :LWK5HPRWHFDOOVWKHFDOOHGPHWKRGLVDOZD\V ZRUNLQJRQDFRS\RIWKHFDOOHU¶VREMHFW :LWKORFDOFDOOVWKHFDOOHGPHWKRGLVDOZD\VZRUNLQJ ZLWKWKHFDOOHU¶VRULJLQDOREMHFW²QRWDFRS\
&KDSWHU
WKHFOLHQWYLHZ
)ZO]UMV\[\W:MUW\M^[TWKITUM\PWL[ /2&$/PHWKRGFDOO 'RJ REMHFW
'RJ¿GR QHZ'RJ
WKLVWUDLQ3HW¿GR ^a\g
a copy of the reference (the remote control) not the Dog object
'RJ
%()25(GRJ UHIHUHQFH
YRLGWUDLQ3HW'RJDUJ ^`
'RJ REMHFW
r and the ÔÞdoÕ Now the ÔargÕ paramel te pies. Both variable are identicaDco object. reference the same og
Yj_ ^a\g 'RJ
%()25(GRJ UHIHUHQFHV
'RJ
5(027(PHWKRGFDOO 'RJ¿GR QHZ'RJ UHPRWH6WXEWUDLQ3HW¿GR
'RJ REMHFW
! NOT the reference value ItÕs a serialized copyctof the actual Dog obje
'RJ REMHFW ^a\g 'RJ
%()25(GRJ UHIHUHQFH
py The server Dog is a co og D t en of the cli
YRLGWUDLQ3HW'RJDUJ ^`
'RJ REMHFW
'RJ REMHFW
^a\g 'RJ
Yj_
&OLHQW
$)7(5GRJV UHIHUHQFHV
'RJ
6HUYHU \RXDUHKHUH
5HPRWHYVORFDO
WKHUH DUH QR
'XPE 4XHVWLRQV
Q:
3O )MSTILLNOTCLEARIFTHE BEAN-534ALWAYSKNOWIFTHECLIENT IS2EMOTEORLOCAL
A:
)TSNOTTHATTHEBEANMUST BUTRATHERTHATTHEBEANMIGHTHAVE TOKNOW)FITMATTERSTHATTHEBEAN ISWORKINGONATHECALLERSOBJECT VIAACOPYOFTHECALLERSREFERENCE ASOPPOSEDTOACOPYOFTHECALLERS OBJECT YOURBEANCODEMIGHTHAVE TOCHANGE!NDTHATGOESFORRETURN VALUESTOO)FITMATTERSTHATTHECALLING METHODGETSBACKACOPYOFAREFER ENCEVSACOPYOFANOBJECT THEBEAN CODEMIGHTHAVETOCHANGE
Q:
"UT)THOUGHTTHATCHOOSINGTO DEPLOYABEANWITHLOCALVS2EMOTE CLIENTVIEWSWASJUSTAMATTEROF SWITCHINGASWITCHATDEPLOYTIME
A:
./././,ETSIMAGINETHAT YOUDIDWRITETWOSETSOFINTERFACES ONEFORALOCALCLIENTVIEWANDONE FORA2EMOTECLIENTVIEW)TISTRUE THATATDEPLOYMENTYOUCOULDDECIDE WHICHOFTHETWOVIEWSYOUWANTEDTO EXPOSEORBOTH "UTTHATWORKSONLY IFTHEBEANCODEDOESNTCAREWHERE THECLIENTIS!BEANMETHODWITHNO ARGUMENTSORRETURNVALUESMIGHTBE SAFEREGARDLESSOFHOWTHECLIENTIS ACCESSINGIT /NESOLUTIONMIGHTBETOWRITETHE BEANCODEASSUMINGTHEBEANIS ALWAYSGETTINGACOPY ANDTHENIFTHE CLIENTISLOCAL HAVETHECLIENTMAKE ACOPYCLONE OFTHEOBJECTBEFORE PASSINGIT/R FORRETURNVALUES YOU MIGHTALWAYSHAVETHEBEANMAKEA COPYBEFOREHANDINGITBACK4HATWAY
&KDSWHU
THEBEANNEVERHASTOWORRYTHATA LOCALCLIENTMIGHTBEMODIFYINGTHE BEANSOBJECT
!NDALOCALCLIENTWONTHAVECODE TOHANDLETHE2EMOTE%XCEPTIONSOR NARROWTHESTUBS
Q:
4HEBOTTOMLINEISTHATDEPLOYINGA BEANWITHA2EMOTEVSLOCALCLIENT VIEWISA"IG$EAL)TSACOMMITMENT 4HECLIENTHASTOKNOWINADVANCE
4HENITSJUSTABOUT ARGUMENTSANDRETURNVALUES)S THEREANYOTHERREASONYOUCOULDNT DEPLOYABEANANDMAKETHE DECISIONFOR2EMOTEVSLOCALVIEWAT DEPLOYTIME
A:
4HEREISANOTHERREASON4HE CLIENTCODE%VENIFTHEBEANDOESNT NEEDTOKNOWHOWITSCLIENTIS ACCESSINGIT THECLIENTMUSTKNOW! CLIENTWRITTENTOACCESSABEANLOCALLY WOULDNTWORKIFTHEBEANS2EMOTE CLIENTINTERFACES ANDVICE VERSA
Q: A:
7HYNOT
4HECLIENTMUSTKNOWIN ADVANCEWHETHERITSACCESSINGA BEANS2EMOTEORLOCALCLIENTVIEW BECAUSETHEINTERFACESTHEMSELVES AREDIFFERENT0OLYMORPHICALLY YOU CANTUSETHE2EMOTEANDLOCAL VIEWSINTERCHANGEABLY BECAUSETHE INTERFACESTHEMSELVESAREDIFFERENT 4HERESNOWAYTHECLIENTCANBE KEPTBLISSFULLYIGNORANT BECAUSE THEBEHAVIOROFTHEBEANISDIFFERENT 2EMEMBER A2EMOTECLIENTMUST HANDLE2EMOTE%XCEPTIONS AND NARROWTHE2EMOTESTUBCOMINGBACK FROMTHELOOKUP!NDA2EMOTECLIENT ISEXPOSEDTOMETHODSINTHEBEANS CLIENTINTERFACESMETHODSTHAT DONTEXISTINTHELOCALINTERFACES3OA 2EMOTECLIENTMIGHT FOREXAMPLE TRY TOCALLAGET(ANDLE METHODONTHE LOCALCOMPONENTINTERFACE AMETHOD CALLTHATWOULDNEVERWORK
Q:
#ANYOUGETAROUNDTHISBY DECLARINGYOUR2EMOTE%XCEPTIONS ONYOURLOCALINTERFACE!NDCOULD YOUMAKEANINTERFACETHATISBOTH 2EMOTEANDLOCALBYHAVING YOURCOMPONENTINTERFACELIKE !DVICE EXTENDBOTH2EMOTEAND %*",OCAL/BJECT7HATSTHEHARM IFTHECLIENTSIMPLYALWAYSHANDLES 2EMOTE%XCEPTIONS ANDALWAYSDOES THENARROW 4HATWAYTHECLIENT SHOULDNTHAVETOKNOW
A:
3TILLWONTWORK&ORONETHING ACCORDINGTOBEANLAW YOURENOT ALLOWEDTODECLARE2EMOTE%XCEPTIONS ONLOCALMETHODS3OTHERESNO GUARANTEETHATYOURSERVERWOULD EVENLETYOUDEPLOYABEANWITH ALOCALINTERFACETHATDECLARES 2EMOTE%XCEPTIONS!NDTHEREISNO GUARANTEETHATTHENARROW METHOD WOULDNOTCAUSEPROBLEMS!NDTHEN THEREAREHANDLESANDALLTHATOTHER STUFF9OUNEEDTOJUSTLETTHISGO
WKHFOLHQWYLHZ
%(WKH&RQWDLQHU (DFKRIWKHFRGHVQLSSHWVRQWKLVSDJHUHSUHVHQWVFRGHIURPHLWKHU DQLQWHUIDFHRUDFOLHQW