Stateful Session EJB: FTP Client Example.. More simply rewritten: Enterprise JavaBeans is a standard server-side component model for distributed business applications.. Most importantly,
Trang 3Enterprise JavaBeans 3.1
Trang 5SIXTH EDITION Enterprise JavaBeans 3.1
Andrew Lee Rubinger and Bill Burke
Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
Trang 6Enterprise JavaBeans 3.1, Sixth Edition
by Andrew Lee Rubinger and Bill Burke
Copyright © 2010 Andrew Lee Rubinger and William J Burke, Jr 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 editionsare also available for most titles (http://my.safaribooksonline.com) For more information, contact ourcorporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com
Editor: Mike Loukides
Production Editor: Teresa Elsey
Copyeditor: Genevieve d’Entremont
Proofreader: Teresa Elsey
Indexer: John Bickelhaupt
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
June 1999: First Edition
March 2000: Second Edition
September 2001: Third Edition
June 2004: Fourth Edition
May 2006: Fifth Edition
September 2010: Sixth Edition
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc Enterprise JavaBeans 3.1, Sixth Edition, the image of a wallaby and joey, and related
trade dress are trademarks of O’Reilly Media, Inc
Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks Where those designations appear in this book, and O’Reilly Media, Inc., was aware of atrademark 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 authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information tained herein
con-ISBN: 978-0-596-15802-6
[M]
1283539129
www.it-ebooks.info
Trang 8Part II Server-Side Component Models
5 The Stateless Session Bean 43
Accessing Environment Properties (Injection and Lookup) 57
6 The Stateful Session Bean 63
vi | Table of Contents
www.it-ebooks.info
Trang 97 The Singleton Session Bean 81
Part III EJB and Persistence
9 Persistence: EntityManager 127
Table of Contents | vii
Trang 1010 Mapping Persistent Objects 151
viii | Table of Contents
www.it-ebooks.info
Trang 1113 Queries, the Criteria API, and JPA QL 205
Table of Contents | ix
Trang 12The WHERE Clause and BETWEEN 221
14 Entity Callbacks and Listeners 235
Part IV Container Services
15 Security 243
16 JNDI, the ENC, and Injection 255
x | Table of Contents
www.it-ebooks.info
Trang 13Transaction Propagation in Bean-Managed Transactions 307
Application Exceptions Versus System Exceptions 313
Trang 14Interceptors and Injection 331
19 Timer Service 341
Example: A Batch Credit Card Processing System 342
javax.ejb.ScheduleExpression and @javax.ejb.Schedule 344
20 EJB 3.1: Web Services Standards 355
The <portType> and <message> Elements 374
The <binding> and <service> Elements 377
21 EJB 3.1 and Web Services 381
The <service-ref> Deployment Element 388
xii | Table of Contents
www.it-ebooks.info
Trang 15Defining a Web Service with JAX-RPC 391
Part V Examples
A FirstEJB Example 415
B Stateless Session EJB: Encryption Example 429
C Stateful Session EJB: FTP Client Example 453
D Singleton Session EJB: RSS Cache Example 505
E Message-Driven EJB: Status Update Listeners Example 527
F Java Persistence APIs: Employee Registry Example 557
G Security: Secured School Example 643
H Transactions: Blackjack Game Example 663
I Interceptors: TV Channel Service Example 691
Table of Contents | xiii
Trang 16J Timer Service: Credit Card Processor Example 719 Index 727
xiv | Table of Contents
www.it-ebooks.info
Trang 17Academia proved a bit abstract to my sophomoric eyes, and after those first few months
of study, I yearned to make programs that delivered real user value Endless error led me to the conclusion that it’s best not to write every little thing on your own—
trial-and-it was more efficient to build upon the work of others.
By then the JBoss open source community was picking up steam with this thing called
an “Application Server,” a neat program that ran other programs To a junior developer
it meant no more networking code No more manual database connections No more object pools or caches It meant no more speaking like a computer It meant writing the programs I wanted to build, not the mechanics underneath.
My experience with this enterprise software miraculously made me marketable enough
to snag a post-college job in the middle of the dot-com fallout, and during my tenure there we enrolled in a weeklong training session from the source—JBoss, Inc.
The reputation of our instructor preceded his arrival, his name sprinkled about the JBoss codebase, popular forums, and the upcoming EJB 3.0 specification Bill Burke came to deliver course material, but in my eyes he planted the seed that it’s possible to become part of a greater community where people talk about software problems, cri- tique one another’s ideas in public, and generally get paid to contribute to the global computing effort.
Over the next few years I stayed active on the user forums and submitted patches, looking to improve upon the new JBoss EJB3 container One day my mail client blinked with an incoming message from the team lead, Carlo de Wolf:
There is an opening for an EJB 3 developer in my team Are you interested?
Why, yes.
xv
Trang 18The ethos of my development from inside JBoss and Red Hat have been the same as they were from the start: keep application programmers writing application code One fall night at a team dinner, Bill extended to me the reins of his hugely successful EJB book from O’Reilly, the same text that initially showed me the ropes This edition
is the product of that discussion.
Who Should Read This Book
This book explains and demonstrates the fundamentals of the EJB 3.1 and Java sistence programming models Although EJB makes application development much simpler, it is still a complex technology that requires a great deal of time and study to master This book provides a straightforward, no-nonsense explanation of the under- lying technology, Java™ classes and interfaces, the component model, and the runtime behavior of EJB It does not include material on previous versions of the specification, however.
Per-Although this book focuses on the fundamentals, it’s not a “dummies” book EJB is an extremely complex and ambitious enterprise technology While using EJB may be fairly simple, the amount of work required to understand and master 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 standing of the basics) to follow the examples in this book If you are unfamiliar with the Java language, I recommend Learning Java ; this book was formerly Exploring Java (both from O’Reilly) If you are unfamiliar with JDBC, I recommend Database Programming with JDBC and Java (O’Reilly) If you need a stronger background in distributed computing, I recommend Java Distributed Computing (O’Reilly).
under-How This Book Is Organized
This book is organized in five parts: Parts I through IV make up the technical script, while Part V comprises the examples The technical manuscript explains what EJB is, how it works, and when to use it Part V provides step-by-step instructions for installing, configuring, and running the examples.
manu-The technical manuscript was adapted from Bill Burke and Richard Monson-Haefel’s fifth edition of this book by yours truly, Andrew Lee Rubinger The code contained herein is not vendor-specific in any way, and it will often value concision over verbose code samples The intent of this section is to focus on conceptual understanding.
xvi | Preface
www.it-ebooks.info
Trang 19Part I, Why Enterprise JavaBeans?
Multiuser distributed system are inherently complex To ignore the issues they present
is to ask for trouble down the line Luckily, you don’t have to do all the work yourself; Chapters 1 through 4 outline the benefits of taking advantage of EJB—a component model for simplified development of enterprise applications.
Part II, Server-Side Component Models
In Chapters 5 through 8 we dive into the mechanics of EJB with relation to business logic We’ll explore the various models available and discuss when each may be appropriate.
Part III, EJB and Persistence
While the server-side component models typically speak to actions, the EJB Entity model addresses the need to interact with persistent state Java Persistence exposes relational data as objects, and EJB comes with integration built-in Chapters 9 through
14 cover these topics.
Part IV, Container Services
EJB is armed with a powerful feature set ensuring secure and consistent execution of your application Chapters 15 through 21 will uncover the utility and configuration of these helpful services Jason T Greene adapted Chapters 20 and 21
Software and Versions
This book covers EJB 3.1 and Java Persistence 2.0 It uses Java language features from the Java SE 6 platform Because the focus of this book is on developing vendor- independent EJB components and solutions, we have stayed away from proprietary extensions and vendor-dependent idioms wherever possible You can use any EJB- compliant server with this book, but you should be familiar with your server’s specific
Preface | xvii
Trang 20installation, deployment, and runtime-management procedures to work with the examples.
Conventions Used in This Book
The following typographical conventions are used in this book:
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values mined by context.
deter-This icon signifies a tip, suggestion, or general note.
This icon signifies a warning or caution.
Using Code Examples
This book is here to help you get your job done In general, you may use the code in this book in your programs and documentation You do not need to contact us for permission; in fact, all example code has open source licensing Selling or distributing
a CD-ROM of text from O’Reilly books does require permission, however Answering
a question by citing this book and quoting example code does not require permission.
We appreciate, but do not require, attribution An attribution usually includes the title,
author, publisher, copyright holder, and ISBN For example: “Enterprise JavaBeans
3.1, Sixth Edition, by Andrew Lee Rubinger and Bill Burke (O’Reilly) Copyright 2010
Andrew Lee Rubinger and William J Burke, Jr., 9780596158026.”
If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at permissions@oreilly.com
xviii | Preface
www.it-ebooks.info
Trang 21Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library online Read books on your cell phone and mobile devices Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors Copy and paste code samples, organize your favorites, down- load chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service To have full digital access to this book and others on similar topics from O’Reilly and other pub- lishers, sign up for free at http://my.safaribooksonline.com
Comments and Questions
Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc.
1005 Gravenstein Highway North
Trang 22Many individuals share the credit for this book’s development and delivery Michael Loukides, the editor, and his team were pivotal to the success of every edition of this book Without their experience, craft, and guidance, this book would not have been possible I want to thank Jason T Greene for taking over the web services chapters I had no desire to learn JAX-WS beyond the @WebService annotation Without the earlier work of Richard Monson-Haefel and Bill Burke, this book would not have been pos- sible It amazes me how the structure of this book could last six editions, and it is a testament to Bill and Richard’s ability to succinctly structure complex topics into a cohesive text.
I particularly want to thank Bill for passing the baton to me on this series A champion
of my career from early on, you’ve encouraged me to get involved in coding, blogging, and accepting new challenges You’ve been a force in our industry since I was learning
a “for” loop, and your continued relevance now in the REST world is incredibly inspiring.
My coworkers, both within JBoss and around the community, have played no small part in the success of my software and this book.
Carlo de Wolf, whether he likes it or not, has been the technical mentor every developer should have He’s invested continually in my growth for years, and it’s difficult to understate my appreciation for both his guidance and friendship.
Jaikiran Pai rounds out our EJB3 team at JBoss Like me, he came from the community, and his dedication to our users and others in our group is noticeable every day, without fail, on our forums and mailing lists You are certainly a jack of all trades.
The Application Server team and members of the #jboss-dev Freenode IRC Channel comprise a support system without which my code would surely be deficient David Lloyd, Jason Greene, Brian Stansberry, Ales Justin, and Bob McWhirter: you boys are brilliant and selfless.
Our newly minted JBoss Testing team brings dedication to usability to a new level Aslak Knutsen, Dan Allen, and Pete Muir: your work has made the examples portion
of this book possible, and I’ve no doubt that we’re on the cusp of a revolution that will bring simplicity back to functional testing of Enterprise Java Let’s keep plugging The JBoss Boston User’s Group gave me a stage and place to geek out with friends Until the next meeting, Jesper Pedersen, Shelly McGowan, Scott Marlow, and John Doyle.
Tim Roberts: You employed me as a college kid and let me learn open source on your dime It was trial by fire, and I thank you for not breaking out the extinguisher before
Trang 23Brian Weisenthal and Morgan Lang of 9mmedia in New York City: Together we built some of the slickest-looking applications I’ve seen to this day You’re deeply successful
in rich media, and it was a pleasure building the backend for such impressive software Thank you for graciously allowing me to pursue a career at JBoss.
Many expert technical reviewers helped ensure that the material was technically rate and true to the spirit of EJB and Java Persistence Of special note are Trenton D Adams and Juraci Paixao Krohling, who’ve sent great comments throughout the process.
accu-I’d also like to thank my personal entourage, though their influence was mostly mental to the completion of this book Prelack, Fleischer, Halbert, Rudman, Clark: You locked me in a moving car and kidnapped me to a casino the weekend before my first draft was due Jonathan Adam: You’re smart and fair, and long ago eclipsed me
detri-in any number of ways No brother could ever be more proud than I am of you Grandma Natalie and Grandpa Jerry Glass, you’ve invested in my education and have encouraged my intellectual curiosity And you make the best bagels-n-lox breakfast known to man.
Mom and Dad, you supported me when you disagreed with me You whipped me into shape when I was lazy You’re excellent at your jobs, and you’re even finer human beings Thank you for being such an excellent example.
Preface | xxi
Trang 25PART I Why Enterprise JavaBeans?
If your path to Enterprise Java is anything like mine, you’ve arrived here hoping to be more productive in application development Perhaps you’ve heard some good or bad things about this thing called “EJB,” and you’d like to explore some more Perhaps some EJB technology is already in place at work, and you’re looking to understand it
a bit deeper.
The fact is that Enterprise JavaBeans is much more than a set of APIs It is a simplified programming model that, when understood at a conceptual level, has the power to easily adapt lightweight Java classes into powerful business components In short, EJB lets you focus on the work you do best—writing your application logic.
In this section we’ll start with a bird’s-eye view of the issues facing every software developer, examining how EJB removes common problems from your concern.
Trang 27CHAPTER 1
Introduction
The Problem Domain
Application development can be a deceivingly complex undertaking.
Not only must our programs do their jobs, they must do them well There’s a laundry list of characteristics that Good Software implies:
And while these are all prerequisites to a finished product, not a single one is specific
to any business Across the world, programmers slave over their terminals, spinning
up custom solutions to the same fundamental issues facing everyone else.
Bluntly put, this is a waste.
Trang 28Core concerns
The primary purpose of an application is to satisfy business logic, the set of rules that dictate its expected behavior More simply, this is what a program does For instance,
an email client must be able to let its users read, compose, send, and organize email.
All functions related to the fulfillment of business logic fall into the category of core
concerns.
Object-oriented principles lend themselves well toward modeling business logic
Typ-ically done via separation of concerns,* a related set of functionality may be mentalized in a module, with well-defined interfaces for how each component will interact outside of its internals (see Figure 1-1 ) In the case of our email client example, this might lead to separate modules for interacting with remote servers, rendering HTML, composing new mail, etc.
compart-Figure 1-1 Modules, each addressing one business use-case, interacting with one another
The core is typically going to contain rules unique to your application, and no one can build it aside from you and your team Our job as software engineers is to realize ideas,
so the more time we can dedicate to business logic, the more efficient we become And the best way to limit our scope to core concerns is to reduce or eliminate the energy we spend everywhere else.
Cross-cutting concerns
While the core of an application defines its primary function, there is a host of secondary operations necessary to keep things running correctly and efficiently Security asser- tions, transactional boundaries, concurrency policies—all are helpful in ensuring the
integrity of the system is in check We define these as aspects.
The problem with aspects is that they’re intrinsically tangential to core concerns In other words, cross-cutting concerns are intended to stretch across modules ( Figure 1-2 ).
* Edsger Dijkstra, “On the role of scientific thought” (1982) http://www.cs.utexas.edu/users/EWD/ transcriptions/EWD04xx/EWD447.html
4 | Chapter 1: Introduction
www.it-ebooks.info
Trang 29This layout paints a picture of perpendicular, or orthogonal, aims For this reason, it
takes great care to integrate aspects with the core in complementary fashion, as opposed
to weighing it down.
While it may seem that aspects violate good practice to separate concerns, in fact they’re quite complementary in design This is because they allow us to reuse shared code across modules, often transparently.
Banking software must allow users to withdraw money from their accounts, but it would make for an interesting solution if we could withdraw from any account we wanted; we need a security assertion at some point to ensure the requesting user has permission If we hardcode this logic into the “withdraw” function, we’ve intermixed security with a core concern, and we’ll likely end up copying/pasting similar checks all over the place A much better approach is to apply security as an common aspect to be shared by many modules and configure where it’s enforced separately.
This configuration ultimately regulates the direction of the invocation chain, but we don’t want to give it too much of our attention.
Plumbing
Once modules have been built to address the core, there’s still the matter of getting data and invocations from point A to point B Plumbing provides this routing, and may take several forms:
• Forwarding control from an HTTP request to some action handler
• Obtaining a JDBC connection or JavaMail session
• Mapping a nonnative request (JSON, ActionScript, RDBMS SQL) into a Java object
Figure 1-2 Aspects working uniformly across modules
The Problem Domain | 5
Trang 30A sufficiently decoupled system defines interfaces for each module This ensures that components may be developed in isolation, limits the need for explicit dependencies, and encourages parallel development All good things.
And like all good things, there’s a cost: integration Plumbing code is nothing more than an adapter between endpoints and provides few merits of its own ( Figure 1-3 ).
Figure 1-3 Plumbing as a connector between core concerns
Perhaps the worst characteristic of the integration layer is that it is notoriously difficult
to test Although Unit Tests, pieces of code that perform assertions on isolated tions, are quite easy to write given a properly designed module, Integration Tests are much more expansive; they typically require a more involved setup of the test envi- ronment, and they may take orders of magnitude longer to invoke This makes for both
func-a process prone to developer lfunc-aziness (tests mfunc-ay not be written!) func-and increfunc-ased time in the build/test cycle.
Plumbing is a means to an end, and therefore of little value in and of itself It will benefit
us to take an approach that minimizes the time we spend getting data from one endpoint
to another As we’ll soon see, we may rely upon standards that remove this bility from our shoulders.
responsi-Code Smart, Not Hard
That’s a lot to consider before even a single line of code is written Ironically, the utions we concoct to address these issues are prone to becoming problems in themselves, and we’re at risk for introducing a tangled mess.
sol-To state the obvious, the more that can be done for us, the less we have to do ourselves.
6 | Chapter 1: Introduction
www.it-ebooks.info
Trang 311 Check that we have permission to register someone new (Security)
2 Start a boundary so everything is ensured to complete together, without affecting
anything else (Transactions)
3 Get a business worker delegate from some pool or cache, so we have control over
concurrency (Performance and Transactional Isolation)
4 Make a hook into the database (Resource Management)
5 Store the user (Business Logic)
6 Get a hook to an SMTP (mail) server (Resource Management)
7 Email a confirmation (Business Logic)
8 Return our worker so another call may use it (Performance and Transactional
Isolation)
9 Close our boundary (Transactions)
Even a simplified example shows that we’re “speaking like a computer.” All this talk about pools and boundaries and databases is undermining the utility of a programming language to help us express our ideas like humans I’d much rather write:
A Container is a host that provides services to guest applications.
The Problem Domain | 7
Trang 32The intent here is to provide generic services upon which applications may rely The service support desired is usually defined by some combination of user code and
metadata that together follow a contract for interaction between the application and
container In the case of Enterprise JavaBeans (EJB) 3.1, this contract is provided by a document jointly developed by experts under the authority of the Java Community Process ( http://jcp.org ) Its job is to do all the work you shouldn’t be doing.
The Enterprise JavaBeans™ 3.1 Specification
Just as interfaces in code abstract the “what” from the “how,” the EJB Specification dictates the capabilities required of a compliant EJB Container This 626-page docu- ment is the result of lessons learned in the field, requests by the community, and sub- sequent debate by the JSR-318 Expert Group ( http://jcp.org/en/jsr/detail?id=318 ).
It is the purpose of this book to introduce concepts provided by the spec in a concise manner, alongside examples where appropriate.
EJB defined
Let’s dig in The Specification defines itself (EJB 3.1 Specification, page 29):
The Enterprise JavaBeans architecture is a [sic] architecture for the development and deployment of component-based business applications Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and multi-user secure These applications may be written once, and then deployed on any server platform that supports the Enterprise JavaBeans specification.
More simply rewritten:
Enterprise JavaBeans is a standard server-side component model for distributed business applications.
This means that EJB defines a model for piecing together a full system by integrating modules Each component may represent a collection of business processes, and these will run centralized on the server ( Figure 1-4 ).
Additionally, the “distributed” nature will provide a mechanism to spread modules across different processes, physical machines, or even entire networks ( Figure 1-5 ).
As we’ll soon discover, EJB is also an aggregate technology; it wires up other facets of the Java Enterprise Edition ( http://java.sun.com/javaee/ ), such as messaging, transac- tions, resource management, persistence, and web services It’s this integration that will reduce the evil plumbing we’d identified earlier.
8 | Chapter 1: Introduction
www.it-ebooks.info
Trang 33Figure 1-5 Using runtime containers to abstract the physical location of code
Embracing the standard of EJB has other, nontechnical benefits Applications that take advantage of EJB architecture are portable across any compliant Container implemen- tation In practice, there may be some retrofitting required in order to resolve vendor- specific features, but applications written to spec alone should stay true to the Sun Microsystems “write once, run anywhere” philosophy of the Java language.
Finally, the familiarity of EJB means that developers already oriented to the technology may spend less time learning the control flow of a particular application, making hiring and training a much more simplified exercise.
Figure 1-4 Modules operating inside a runtime container
The Problem Domain | 9
Trang 34We’ve seen requirements common to many applications and how these can be met without recoding the same stuff the company across the street did last week We’ve discussed the importance of keeping business logic uncluttered with cross-cutting con- cerns And we’ve cringed at the unnecessary plumbing employed by the roll-your-own approach.
Most importantly, we’ve revealed the EJB Specification as a viable solution to:
• Address common/generic issues within application development
• Code less
• Standardize
• Integrate with other technologies under the umbrella of the Java Enterprise Edition The specification offers a few different bean types, and the most sensible choice will depend upon the intended purpose.
10 | Chapter 1: Introduction
www.it-ebooks.info
Trang 35CHAPTER 2
Component Types
Modeling real-life objects and concepts is one of the first skills a programmer must develop As such, we’ve become fairly adept at implementing object-oriented axioms such as reusability and extensibility on a daily basis When we focus these principles
on business logic, we end up with a set of business objects that encapsulate the rules of
devel-Because a POJO class is just like any other class, it does not become an EJB until it’s:
1 Assembled/packaged
2 Deployed
3 Accessed via the Container
This is an important distinction EJBs become such only in the context of the EJB Container.
The Container, in turn, is responsible for equipping POJOs with EJB Services (covered
in Chapter 3 ) as well as exposing their behavior via one of three personalities We call
these personalities component types, and while implementing their semantics is beyond
scope for an application developer, it’s important to know how, by contract, they’ll behave.
We’ll use the example of a fictitious casino to showcase where each component type might be applied.
* Fowler et al http://www.martinfowler.com/bliki/POJO.html
11
Trang 36Server-Side Component Types
Server-side component types reside exclusively on the server, and the client must teract with them via some indirection There are two major server-side component types: session beans, which expose a view for the client to invoke upon, and message- driven beans, which act as event listeners.
in-Session Beans
If EJB is a grammar, session beans are the verbs They take action, and they frequently contain business methods Because of EJB’s distributed nature, underlying bean in- stances that carry out the invocation live on the server and are accessed by way of a simple view the client may request of the EJB Container This means that the client does not access the EJB directly, which allows the Container to perform all sorts of magic before a request finally hits the target method It’s this separation that allows for the client to be completely unaware of the location of the server, concurrency policies,
or queuing of requests to manage resources As far as the client is concerned, it’s
op-erating directly upon an EJB In truth, the client is invoking upon a proxy reference that
will delegate the request along to the Container and return the appropriate response (see Figure 2-1 ).
Figure 2-1 Client invoking upon a proxy object, responsible for delegating the call along to the EJB Container
Ultimately, it’s the bean instances created and managed by the Container that the service
client requests.
Stateless session beans (SLSBs)
Stateless session beans are useful for functions in which state does not need to be carried from invocation to invocation A client cannot assume that subsequent requests will
12 | Chapter 2: Component Types
www.it-ebooks.info
Trang 37target any particular bean instance In fact, the Container will often create and destroy instances however it feels will be most efficient (see Figure 2-2 ) How a Container chooses the target instance is left to the vendor’s discretion.
Figure 2-2 An SLSB Instance Selector picking an instance at random
Because there’s no rule linking an invocation to a particular target bean instance, these instances may be used interchangeably and shared by many clients This allows the Container to hold a much smaller number of objects in service, hence keeping memory footprint down.
One caveat to beware: though a SLSB has stateless semantics, it’s backed by an instance
of a class created by the application developer Particular care must be employed to assure that any shared members (instance variables, for instance) are not leaked be- tween invocations; this may lead to unpredictable behavior We’ll explain this gotcha when we cover SLSBs in greater detail in Chapter 5
If we were to give our casino a game of roulette, SLSB would be a natural tation choice Roulette is a game with no memory—each spin operates independently from the last—so a function getSpinResult should return a random spot on the wheel.
implemen-Stateful session beans (SFSBs)
Stateful session beans differ from SLSBs in that every request upon a given proxy erence is guaranteed to ultimately invoke upon the same bean instance This is to say,
ref-SFSB invocations share conversational state Each ref-SFSB proxy object has an isolated
session context, so calls to one session will not affect another.
Stateful sessions, and their corresponding bean instances, are created sometime before the first invocation upon a proxy is made to its target instance ( Figure 2-3 ) They live
until the client invokes a method that the bean provider has marked as a remove event,
or until the Container decides to evict the session (usually due to some timeout, though the spec leaves this out-of-scope and up to the vendor).
Server-Side Component Types | 13
Trang 38In order to minimize the number of stateful sessions carried around in memory, the
Container may passivate a SFSB bean instance During passivation, the session’s state
is flushed to some persistent storage such that it may be removed from RAM If the
session is needed again before it’s removed for good, the Container will activate it and
bring the bean instance back into memory.
No casino is complete without a good game of poker, and we could build ours using SFSBs Each game is played using a single deck, and we need to keep track of which cards have already been dealt—otherwise we risk giving the player next to us the im- possible hand of five aces! If each table is scoped to its own stateful session, we could ensure that the integrity of the deck is intact.
We’ll dive into SFSBs in Chapter 6
Singleton beans
Sometimes we don’t need any more than one backing instance for our business objects EJB 3.1 therefore introduces a new session component type, the singleton bean Because all requests upon a singleton are destined for the same bean instance, the Container doesn’t have much work to do in choosing the target ( Figure 2-4 ).
The singleton session bean may be marked to eagerly load when an application is ployed; therefore, it may be leveraged to fire application lifecycle events This draws a relationship where deploying a singleton bean implicitly leads to the invocation of its lifecycle callbacks We’ll put this to good use when we discuss singleton beans in
de-Chapter 7
Dealers in a casino aren’t granted complete autonomy; they’ve got to clear a set of privileged tasks such as changing money, cashout, and large betting with the pit boss The pit boss, in turn, is the sole authority over what’s permitted on his floor If we model the boss as a singleton, all requests are passed along to the same source—one
Figure 2-3 Stateful session bean creating and using the correct client instance, which lives inside the EJB Container, to carry out the invocation
14 | Chapter 2: Component Types
www.it-ebooks.info
Trang 39able to make informed, consistent decisions In addition, at the start of the pit boss’s shift, he can make the rounds and do whatever startup tasks he deems necessary.
Message-Driven Beans (MDBs)
Asynchronous messaging is a paradigm in which two or more applications cate via a message describing a business event EJB 3.1 interacts with messaging systems via the Java Connector Architecture (JCA) 1.6 ( http://jcp.org/en/jsr/detail?id=322 ), which acts as an abstraction layer that enables any system to be adapted as a valid
communi-sender The message-driven bean, in turn, is a listener that consumes messages and may
either handle them directly or delegate further processing to other EJB components The asynchronous characteristic of this exchange means that a message sender is not waiting for a response, so no return to the caller is provided ( Figure 2-5 ).
Figure 2-5 Asynchronous invocation of a message-driven bean, which acts as a listener for incoming events
One common provider of asynchronous messaging is the Java Message Service (JMS), and the EJB specification dictates that JMS is supported implicitly.† If a message is sent
Figure 2-4 Conceptual diagram of a singleton session bean with only one backing bean instance
† EJB 3.1 Specification 5.4.17.1
Server-Side Component Types | 15
Trang 40to a JMS Topic or Queue, an MDB may be created to take action upon that event By extension, any service with a valid JCA Resource Adapter may use MDB as an endpoint We’ll untangle the various technologies that piece together asynchronous messaging
in Chapter 8
Like SLSBs, MDBs have no conversational state Any instance may be used in servicing
a message In fact, the client has no view or knowledge of the MDB at all! Once the client sends a message, it’s out of scope to worry about what may be listening to the event fired.
After a full night of gambling, visitors to our casino are likely to need their cars back from the valet We may provide our valet service via MDBs; once a ticket (message) is received, the valet should fetch the car while its owner continues on to grab a cup of coffee or visit the gift shop The casino visitor will have to frequently check back to see whether his car has arrived.
Message-driven beans are explored in Chapter 8
Entity Beans
While session beans are our verbs, entity beans are the nouns Their aim is to express
an object view of resources stored within a Relational Database Management System (RDBMS)—a process commonly known as object-relational mapping.
Like session beans, the entity type is modeled as a POJO, and becomes a managed
javax.persistence.EntityManager , a container-supplied service that tracks state changes and synchronizes with the database as necessary A client who alters the state
of an entity bean may expect any altered fields to be propagated to persistent storage Frequently the EntityManager will cache both reads and writes to transparently stream- line performance, and may enlist with the current transaction to flush state to persistent storage automatically upon invocation completion ( Figure 2-6 ).
Figure 2-6 Using an EntityManager to map between POJO object state and a persistent relational database
Unlike session beans and MDBs, entity beans are not themselves a server-side nent type Instead, they are a view that may be detached from management and used
compo-16 | Chapter 2: Component Types
www.it-ebooks.info