Enterprise JavaBeans 3.1
SIXTH EDITIONEnterprise JavaBeans 3.1  Andrew Lee Rubinger and Bill Burke    Beijing • Cambridge • Farnham • Köln • Sebast...
Enterprise JavaBeans 3.1, Sixth Editionby Andrew Lee Rubinger and Bill BurkeCopyright © 2010 Andrew Lee Rubinger and Willi...
Table of ContentsPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....
Platform Integration                                                                                                 27   ...
7. The Singleton Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...
A Transactional Abstraction                                                                                     141       ...
Cascading                                                                                                              191...
The WHERE Clause and BETWEEN                                                                                             2...
EntityManagerFactory References                                                                                     266   ...
Interceptors and Injection                                                                                              33...
Defining a Web Service with JAX-RPC                                                                                    391...
J. Timer Service: Credit Card Processor Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719Index . . ....
PrefaceAuthor’s NoteReluctantly succumbing to my father’s urging in the spring of 2000, I enrolled in myfirst software dev...
The ethos of my development from inside JBoss and Red Hat have been the same asthey were from the start: keep application ...
Part I, Why Enterprise JavaBeans?Multiuser distributed system are inherently complex. To ignore the issues they presentis ...
installation, deployment, and runtime-management procedures to work with theexamples.Conventions Used in This BookThe foll...
Safari® Books Online             Safari Books Online is an on-demand digital library that lets you easily             sear...
AcknowledgmentsMany individuals share the credit for this book’s development and delivery. MichaelLoukides, the editor, an...
Brian Weisenthal and Morgan Lang of 9mmedia in New York City: Together we builtsome of the slickest-looking applications I...
PART I              Why Enterprise JavaBeans?If your path to Enterprise Java is anything like mine, you’ve arrived here ho...
CHAPTER 1                                                           IntroductionThe Problem DomainApplication development ...
Core concernsThe primary purpose of an application is to satisfy business logic, the set of rules thatdictate its expected...
Figure 1-2. Aspects working uniformly across modulesThis layout paints a picture of perpendicular, or orthogonal, aims. Fo...
A sufficiently decoupled system defines interfaces for each module. This ensures thatcomponents may be developed in isolat...
Do lessWhile it’s a likely requirement that business logic be unique to your application, themachinery that moves things a...
The intent here is to provide generic services upon which applications may rely. Theservice support desired is usually def...
Figure 1-4. Modules operating inside a runtime containerFigure 1-5. Using runtime containers to abstract the physical loca...
ReviewWe’ve seen requirements common to many applications and how these can be metwithout recoding the same stuff the comp...
CHAPTER 2                                                        Component TypesModeling real-life objects and concepts is...
Server-Side Component TypesServer-side component types reside exclusively on the server, and the client must in-teract wit...
target any particular bean instance. In fact, the Container will often create and destroyinstances however it feels will b...
Figure 2-3. Stateful session bean creating and using the correct client instance, which lives inside theEJB Container, to ...
Figure 2-4. Conceptual diagram of a singleton session bean with only one backing bean instanceable to make informed, consi...
to a JMS Topic or Queue, an MDB may be created to take action upon that event. Byextension, any service with a valid JCA R...
just like any stateful object. When detached (disassociated from the EntityManager),there is no database association, but ...
CHAPTER 3                                                       Container ServicesWe see examples of efficient processes e...
• Interceptors • Java Enterprise Platform integrationWe’ll introduce each at a high level here, and get into further detai...
ConcurrencyAssuming each Service is represented by one instance, dependency injection alone is afine solution for a single...
Conversely, if the service was permitted to use any number of underlying instances,there would be no guard to say how many...
TransactionsAs a routine chugs along, it may perform half of its duties before encountering someexceptional circumstance t...
teller and a branch manager when confronted with a request to approve a loan, andmanually baking this logic into the busin...
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Enterprise java beans 3.1 6th edition
Upcoming SlideShare
Loading in...5
×

Enterprise java beans 3.1 6th edition

9,700

Published on

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
9,700
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
201
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Enterprise java beans 3.1 6th edition"

  1. 1. Enterprise JavaBeans 3.1
  2. 2. SIXTH EDITIONEnterprise JavaBeans 3.1 Andrew Lee Rubinger and Bill Burke Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
  3. 3. Enterprise JavaBeans 3.1, Sixth Editionby Andrew Lee Rubinger and Bill BurkeCopyright © 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 Indexer: John BickelhauptProduction Editor: Teresa Elsey Cover Designer: Karen MontgomeryCopyeditor: Genevieve d’Entremont Interior Designer: David FutatoProofreader: Teresa Elsey Illustrator: Robert RomanoPrinting 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 ofO’Reilly Media, Inc. Enterprise JavaBeans 3.1, Sixth Edition, the image of a wallaby and joey, and relatedtrade 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 assumeno responsibility for errors or omissions, or for damages resulting from the use of the information con-tained herein.ISBN: 978-0-596-15802-6[M]1283539129
  4. 4. Table of ContentsPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvPart I. Why Enterprise JavaBeans? 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 The Problem Domain 3 Breaking Up Responsibilities 3 Code Smart, Not Hard 6 The Enterprise JavaBeans™ 3.1 Specification 8 Review 10 2. Component Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Server-Side Component Types 12 Session Beans 12 Message-Driven Beans (MDBs) 15 Entity Beans 16 The Java Persistence Model 17 The Model Isn’t Everything 17 3. Container Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Dependency Injection (DI) 20 Concurrency 21 Instance Pooling/Caching 21 Transactions 23 Security 23 Timers 24 Naming and Object Stores 24 Interoperability 25 Lifecycle Callbacks 25 Interceptors 26 v
  5. 5. Platform Integration 27 Bringing It Together 27 4. Developing Your First EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Step 1: Preparation 29 Definitions 29 Naming Conventions 32 Conventions for the Examples 32 Step 2: Coding the EJB 33 The Contract 33 The Bean Implementation Class 34 Out-of-Container Testing 35 Integration Testing 36 Summary 39Part II. Server-Side Component Models 5. The Stateless Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 The XML Deployment Descriptor 45 SessionContext 46 EJBContext 47 The Lifecycle of a Stateless Session Bean 49 The Does Not Exist State 50 The Method-Ready Pool 50 Example: The EncryptionEJB 52 The Contract: Business Interfaces 53 Application Exceptions 54 Bean Implementation Class 55 Accessing Environment Properties (Injection and Lookup) 57 Asynchronous Methods 60 6. The Stateful Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 The Lifecycle of a Stateful Session Bean 64 The Does Not Exist State 65 The Method-Ready State 65 The Passivated State 66 Example: The FileTransferEJB 68 The Contract: Business Interfaces 69 Exceptions 70 Bean Implementation Class 70 POJO Testing Outside the Container 74 Integration Testing 77vi | Table of Contents
  6. 6. 7. The Singleton Session Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Concurrency 82 Shared Mutable Access 84 Container-Managed Concurrency 86 Bean-Managed Concurrency 87 Lifecycle 87 Explicit Startup 87 Example: The RSSCacheEJB 88 Value Objects 89 The Contract: Business Interfaces 92 Bean Implementation Class 92 8. Message-Driven Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 JMS and Message-Driven Beans 98 JMS as a Resource 98 JMS Is Asynchronous 99 JMS Messaging Models 100 Learning More About JMS 103 JMS-Based Message-Driven Beans 103 @MessageDriven 103 The Lifecycle of a Message-Driven Bean 108 The Does Not Exist State 109 The Method-Ready Pool 109 Connector-Based Message-Driven Beans 111 Message Linking 114 Session Beans Should Not Receive Messages 114 The JMS APIs 115 Example: The StatusUpdateEJBs 118Part III. EJB and Persistence 9. Persistence: EntityManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Entities Are POJOs 128 Managed Versus Unmanaged Entities 130 Persistence Context 130 Packaging a Persistence Unit 133 The Persistence Unit Class Set 135 Obtaining an EntityManager 136 EntityManagerFactory 137 Obtaining a Persistence Context 138 Interacting with an EntityManager 140 Example: A Persistent Employee Registry 141 Table of Contents | vii
  7. 7. A Transactional Abstraction 141 Persisting Entities 142 Finding and Updating Entities 144 Removing Entities 147 refresh() 148 contains() and clear() 148 flush() and FlushModeType 148 Locking 149 unwrap() and getDelegate() 149 10. Mapping Persistent Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 The Programming Model 152 The Employee Entity 152 The Bean Class 152 XML Mapping File 154 Basic Relational Mapping 155 Elementary Schema Mappings 155 Primary Keys 157 @Id 157 Table Generators 158 Sequence Generators 159 Primary-Key Classes and Composite Keys 160 Property Mappings 164 @Transient 164 @Basic and FetchType 164 @Lob 166 @Temporal 166 @Enumerated 167 @Embedded Objects 167 11. Entity Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 The Seven Relationship Types 171 One-to-One Unidirectional Relationship 173 One-to-One Bidirectional Relationship 176 One-to-Many Unidirectional Relationship 178 Many-to-One Unidirectional Relationship 181 One-to-Many Bidirectional Relationship 182 Many-to-Many Bidirectional Relationship 184 Many-to-Many Unidirectional Relationship 187 Mapping Collection-Based Relationships 188 Ordered List-Based Relationship 188 Map-Based Relationship 189 Detached Entities and FetchType 190viii | Table of Contents
  8. 8. Cascading 191 PERSIST 192 MERGE 192 REMOVE 193 REFRESH 193 ALL 193 When to Use Cascading 19412. Entity Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Single Table per Class Hierarchy 196 Advantages 198 Disadvantages 198 Table per Concrete Class 199 Advantages 200 Disadvantages 200 Table per Subclass 200 Advantages 203 Disadvantages 203 Mixing Strategies 203 Nonentity Base Classes 20313. Queries, the Criteria API, and JPA QL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Query API 206 Parameters 208 Date Parameters 209 Paging Results 209 Hints 210 FlushMode 210 JPA QL 211 Abstract Schema Names 211 Simple Queries 212 Selecting Entity and Relationship Properties 213 Constructor Expressions 215 The IN Operator and INNER JOIN 215 LEFT JOIN 216 Fetch Joins 217 Using DISTINCT 217 The WHERE Clause and Literals 218 The WHERE Clause and Operator Precedence 218 The WHERE Clause and Arithmetic Operators 219 The WHERE Clause and Logical Operators 219 The WHERE Clause and Comparison Symbols 219 The WHERE Clause and Equality Semantics 220 Table of Contents | ix
  9. 9. The WHERE Clause and BETWEEN 221 The WHERE Clause and IN 221 The WHERE Clause and IS NULL 222 The WHERE Clause and IS EMPTY 223 The WHERE Clause and MEMBER OF 223 The WHERE Clause and LIKE 224 Functional Expressions 224 The ORDER BY Clause 228 Bulk UPDATE and DELETE 229 Native Queries 230 Scalar Native Queries 230 Simple Entity Native Queries 230 Complex Native Queries 231 Named Queries 232 Named Native Queries 233 14. Entity Callbacks and Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Callback Events 235 Callbacks on Entity Classes 236 Entity Listeners 237 Default Entity Listeners 238 Inheritance and Listeners 238Part IV. Container Services 15. Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 Authentication and Identity 244 Authorization 245 Example: A Secured School 246 The Business Interface 246 Assigning Method Permissions 247 Programmatic Security 249 The RunAs Security Identity 251 16. JNDI, the ENC, and Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 Global JNDI 255 The JNDI ENC 256 What Can Be Registered in the JNDI ENC? 257 How Is the JNDI ENC Populated? 257 How Are Things Referenced from the ENC? 258 Reference and Injection Types 264 EJB References 264x | Table of Contents
  10. 10. EntityManagerFactory References 266 EntityManager References 269 Resource References 271 Resource Environment and Administered Objects 275 Environment Entries 275 Message Destination References 27717. Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 ACID Transactions 279 Example: The BlackjackEJB 281 Helper EJBs for Testing Transactions 283 Is the BlackjackEJB Atomic? 284 Is the BlackjackEJB Consistent? 285 Is the BlackjackEJB Isolated? 285 Is the BlackjackEJB Durable? 285 Declarative Transaction Management 286 Transaction Scope 286 Transaction Attributes 287 Transaction Propagation 293 Isolation and Database Locking 298 Dirty, Repeatable, and Phantom Reads 298 Database Locks 299 Transaction Isolation Levels 300 Balancing Performance Against Consistency 301 Optimistic Locking 302 Programmatic Locking 303 Nontransactional EJBs 303 Explicit Transaction Management 304 Transaction Propagation in Bean-Managed Transactions 307 Heuristic Decisions 308 UserTransaction 309 Status 310 EJBContext Rollback Methods 312 Exceptions and Transactions 313 Application Exceptions Versus System Exceptions 313 Transactional Stateful Session Beans 318 The Transactional Method-Ready State 320 Conversational Persistence Contexts 32118. Interceptors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Intercepting Methods 323 Interceptor Class 325 Applying Interceptors 327 Table of Contents | xi
  11. 11. Interceptors and Injection 331 Intercepting Lifecycle Events 333 Custom Injection Annotations 333 Exception Handling 335 Aborting a Method Invocation 336 Catch and Rethrow Exceptions 336 Interceptor Lifecycle 338 Bean Class @AroundInvoke Methods 338 19. Timer Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 Example: A Batch Credit Card Processing System 342 The Business Interface 343 javax.ejb.ScheduleExpression and @javax.ejb.Schedule 344 The Bean Implementation Class 345 The TimerService 347 The Timer 348 Transactions 350 Stateless Session Bean Timers 351 Message-Driven Bean Timers 352 20. EJB 3.1: Web Services Standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Web Services Overview 355 XML Schema and XML Namespaces 356 XML Schema 356 XML Namespaces 361 SOAP 1.1 368 Web Services Styles 369 Exchanging SOAP Messages with HTTP 370 Now You See It, Now You Don’t 370 WSDL 1.1 371 The <definitions> Element 372 The <portType> and <message> Elements 374 The <types> Element 375 The <binding> and <service> Elements 377 UDDI 2.0 379 From Standards to Implementation 380 21. EJB 3.1 and Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 Accessing Web Services with JAX-RPC 381 Generating JAX-RPC Artifacts from WSDL 382 Calling a Service from an EJB 387 The <service-ref> Deployment Element 388 The JAX-RPC Mapping File 389xii | Table of Contents
  12. 12. Defining a Web Service with JAX-RPC 391 The WSDL Document 392 The Service Endpoint Interface 393 The Stateless Bean Class 393 The Deployment Files 394 Using JAX-WS 396 The @WebService Annotation 396 The @WebMethod Annotation 397 The @SOAPBinding Annotation 398 The @WebParam Annotation 399 The @WebResult Annotation 400 The @OneWay Annotation 401 Separating the Web Services Contract 401 The Service Class 402 The Service Endpoint Interface 403 The @WebServiceRef Annotation 403 Other Annotations and APIs 405 JAXB 405 Taking JAXB Further 407 Conclusion 407Part 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
  13. 13. J. Timer Service: Credit Card Processor Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727xiv | Table of Contents
  14. 14. PrefaceAuthor’s NoteReluctantly succumbing to my father’s urging in the spring of 2000, I enrolled in myfirst software development course at the University of Massachusetts. Following yearsof frustration getting my computer to “just do what I want,” I quickly found our rolesinverted; I was in charge of the machine.Academia proved a bit abstract to my sophomoric eyes, and after those first few monthsof study, I yearned to make programs that delivered real user value. Endless trial-and-error led me to the conclusion that it’s best not to write every little thing on your own—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 calledan “Application Server,” a neat program that ran other programs. To a junior developerit meant no more networking code. No more manual database connections. No moreobject pools or caches. It meant no more speaking like a computer. It meant writingthe programs I wanted to build, not the mechanics underneath.My experience with this enterprise software miraculously made me marketable enoughto snag a post-college job in the middle of the dot-com fallout, and during my tenurethere we enrolled in a weeklong training session from the source—JBoss, Inc.The reputation of our instructor preceded his arrival, his name sprinkled about theJBoss codebase, popular forums, and the upcoming EJB 3.0 specification. Bill Burkecame to deliver course material, but in my eyes he planted the seed that it’s possible tobecome 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 globalcomputing 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 blinkedwith 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
  15. 15. The ethos of my development from inside JBoss and Red Hat have been the same asthey 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 successfulEJB book from O’Reilly, the same text that initially showed me the ropes. This editionis the product of that discussion.Who Should Read This BookThis book explains and demonstrates the fundamentals of the EJB 3.1 and Java Per-sistence programming models. Although EJB makes application development muchsimpler, it is still a complex technology that requires a great deal of time and study tomaster. This book provides a straightforward, no-nonsense explanation of the under-lying technology, Java™ classes and interfaces, the component model, and the runtimebehavior of EJB. It does not include material on previous versions of the specification,however.Although this book focuses on the fundamentals, it’s not a “dummies” book. EJB is anextremely complex and ambitious enterprise technology. While using EJB may be fairlysimple, the amount of work required to understand and master EJB is significant. Beforereading this book, you should be fluent in the Java language and have some practicalexperience developing business solutions. Experience with distributed object systemsis not a must, but you will need some experience with JDBC (or at least an under-standing of the basics) to follow the examples in this book. If you are unfamiliar withthe Java language, I recommend Learning Java; this book was formerly ExploringJava (both from O’Reilly). If you are unfamiliar with JDBC, I recommend DatabaseProgramming with JDBC and Java (O’Reilly). If you need a stronger background indistributed computing, I recommend Java Distributed Computing (O’Reilly).How This Book Is OrganizedThis book is organized in five parts: Parts I through IV make up the technical manu-script, while Part V comprises the examples. The technical manuscript explains whatEJB is, how it works, and when to use it. Part V provides step-by-step instructions forinstalling, configuring, and running the examples.The technical manuscript was adapted from Bill Burke and Richard Monson-Haefel’sfifth edition of this book by yours truly, Andrew Lee Rubinger. The code containedherein is not vendor-specific in any way, and it will often value concision over verbosecode samples. The intent of this section is to focus on conceptual understanding.xvi | Preface
  16. 16. Part I, Why Enterprise JavaBeans?Multiuser distributed system are inherently complex. To ignore the issues they presentis 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 componentmodel for simplified development of enterprise applications.Part II, Server-Side Component ModelsIn Chapters 5 through 8 we dive into the mechanics of EJB with relation to businesslogic. We’ll explore the various models available and discuss when each may beappropriate.Part III, EJB and PersistenceWhile the server-side component models typically speak to actions, the EJB Entitymodel addresses the need to interact with persistent state. Java Persistence exposesrelational data as objects, and EJB comes with integration built-in. Chapters 9 through14 cover these topics.Part IV, Container ServicesEJB is armed with a powerful feature set ensuring secure and consistent execution ofyour application. Chapters 15 through 21 will uncover the utility and configuration ofthese helpful services. Jason T. Greene adapted Chapters 20 and 21.Part V, ExamplesThe examples workbook shows how to execute examples from those chapters in thebook that include at least one significant example. You’ll want to read the introductionto the workbook to set up your build environment and configure it to run the examples.After that, just go to the workbook chapter that matches the chapter you’re reading.The examples themselves will have a release cycle that outlives this book, so you maywant to check back to get bug fixes, enhancements, and other updates as time goes on.Software and VersionsThis book covers EJB 3.1 and Java Persistence 2.0. It uses Java language features fromthe Java SE 6 platform. Because the focus of this book is on developing vendor-independent EJB components and solutions, we have stayed away from proprietaryextensions 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
  17. 17. installation, deployment, and runtime-management procedures to work with theexamples.Conventions Used in This BookThe following typographical conventions are used in this book:Italic Indicates new terms, URLs, email addresses, filenames, and file extensions.Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.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 deter- mined by context. This icon signifies a tip, suggestion, or general note. This icon signifies a warning or caution.Using Code ExamplesThis book is here to help you get your job done. In general, you may use the code inthis book in your programs and documentation. You do not need to contact us forpermission; in fact, all example code has open source licensing. Selling or distributinga CD-ROM of text from O’Reilly books does require permission, however. Answeringa 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 JavaBeans3.1, Sixth Edition, by Andrew Lee Rubinger and Bill Burke (O’Reilly). Copyright 2010Andrew 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
  18. 18. Safari® 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 areavailable for print, and get exclusive access to manuscripts in development and postfeedback for the authors. Copy and paste code samples, organize your favorites, down-load chapters, bookmark key sections, create notes, print out pages, and benefit fromtons of other time-saving features.O’Reilly Media has uploaded this book to the Safari Books Online service. To have fulldigital 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 QuestionsPlease address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax)There is a web page for this book, which lists errata, examples, and any additionalinformation. You can access this page at: http://oreilly.com/catalog/9780596158026To comment on or ask technical questions about this book, send email to: bookquestions@oreilly.comFor more information about books, conferences, software, Resource Centers, and theO’Reilly Network, see the O’Reilly website at: http://www.oreilly.com Preface | xix
  19. 19. AcknowledgmentsMany individuals share the credit for this book’s development and delivery. MichaelLoukides, the editor, and his team were pivotal to the success of every edition of thisbook. Without their experience, craft, and guidance, this book would not have beenpossible. I want to thank Jason T. Greene for taking over the web services chapters. Ihad no desire to learn JAX-WS beyond the @WebService annotation. Without the earlierwork 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 atestament to Bill and Richard’s ability to succinctly structure complex topics into acohesive text.I particularly want to thank Bill for passing the baton to me on this series. A championof 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 learninga “for” loop, and your continued relevance now in the REST world is incrediblyinspiring.My coworkers, both within JBoss and around the community, have played no smallpart in the success of my software and this book.Carlo de Wolf, whether he likes it or not, has been the technical mentor every developershould have. He’s invested continually in my growth for years, and it’s difficult tounderstate 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, withoutfail, 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 Channelcomprise a support system without which my code would surely be deficient. DavidLloyd, Jason Greene, Brian Stansberry, Ales Justin, and Bob McWhirter: you boys arebrilliant 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 portionof this book possible, and I’ve no doubt that we’re on the cusp of a revolution that willbring 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 JohnDoyle.Tim Roberts: You employed me as a college kid and let me learn open source on yourdime. It was trial by fire, and I thank you for not breaking out the extinguisher beforeI developed my chops.Marc Elliott and Matt Warren: You gave me my first job out of school, and your pa-tience in cultivating a useful employee out of me will always be remembered.xx | Preface
  20. 20. Brian Weisenthal and Morgan Lang of 9mmedia in New York City: Together we builtsome of the slickest-looking applications I’ve seen to this day. You’re deeply successfulin 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 accu-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 theprocess.I’d also like to thank my personal entourage, though their influence was mostly detri-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 myfirst draft was due. Jonathan Adam: You’re smart and fair, and long ago eclipsed mein 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 haveencouraged my intellectual curiosity. And you make the best bagels-n-lox breakfastknown to man.Mom and Dad, you supported me when you disagreed with me. You whipped me intoshape when I was lazy. You’re excellent at your jobs, and you’re even finer humanbeings. Thank you for being such an excellent example. Preface | xxi
  21. 21. PART I Why Enterprise JavaBeans?If your path to Enterprise Java is anything like mine, you’ve arrived here hoping to bemore productive in application development. Perhaps you’ve heard some good or badthings about this thing called “EJB,” and you’d like to explore some more. Perhapssome EJB technology is already in place at work, and you’re looking to understand ita bit deeper.The fact is that Enterprise JavaBeans is much more than a set of APIs. It is a simplifiedprogramming model that, when understood at a conceptual level, has the power toeasily adapt lightweight Java classes into powerful business components. In short, EJBlets 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 softwaredeveloper, examining how EJB removes common problems from your concern.
  22. 22. CHAPTER 1 IntroductionThe Problem DomainApplication development can be a deceivingly complex undertaking.Not only must our programs do their jobs, they must do them well. There’s a laundrylist of characteristics that Good Software implies: • Secure • Sound/maintains integrity • Scalable • Interoperable • Robust/resilient • Correct/functions as specifiedAnd while these are all prerequisites to a finished product, not a single one is specificto any business. Across the world, programmers slave over their terminals, spinningup custom solutions to the same fundamental issues facing everyone else.Bluntly put, this is a waste.Breaking Up ResponsibilitiesFor the sake of simplicity, we may categorize all code in a system into one of threeflavors: • Core concerns • Cross-cutting concerns • Plumbing 3
  23. 23. Core concernsThe primary purpose of an application is to satisfy business logic, the set of rules thatdictate 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 coreconcerns.Object-oriented principles lend themselves well toward modeling business logic. Typ-ically done via separation of concerns,* a related set of functionality may be compart-mentalized in a module, with well-defined interfaces for how each component willinteract 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, renderingHTML, composing new mail, etc.Figure 1-1. Modules, each addressing one business use-case, interacting with one anotherThe core is typically going to contain rules unique to your application, and no one canbuild 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. Andthe best way to limit our scope to core concerns is to reduce or eliminate the energy wespend everywhere else.Cross-cutting concernsWhile the core of an application defines its primary function, there is a host of secondaryoperations necessary to keep things running correctly and efficiently. Security asser-tions, transactional boundaries, concurrency policies—all are helpful in ensuring theintegrity of the system is in check. We define these as aspects.The problem with aspects is that they’re intrinsically tangential to core concerns. Inother 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.html4 | Chapter 1: Introduction
  24. 24. Figure 1-2. Aspects working uniformly across modulesThis layout paints a picture of perpendicular, or orthogonal, aims. For this reason, ittakes great care to integrate aspects with the core in complementary fashion, as opposedto weighing it down.While it may seem that aspects violate good practice to separate concerns, in fact they’requite complementary in design. This is because they allow us to reuse shared codeacross modules, often transparently.Banking software must allow users to withdraw money from their accounts, but itwould make for an interesting solution if we could withdraw from any account wewanted; we need a security assertion at some point to ensure the requesting user haspermission. If we hardcode this logic into the “withdraw” function, we’ve intermixedsecurity with a core concern, and we’ll likely end up copying/pasting similar checks allover the place. A much better approach is to apply security as an common aspect to beshared by many modules and configure where it’s enforced separately.This configuration ultimately regulates the direction of the invocation chain, but wedon’t want to give it too much of our attention.PlumbingOnce modules have been built to address the core, there’s still the matter of gettingdata and invocations from point A to point B. Plumbing provides this routing, and maytake 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 The Problem Domain | 5
  25. 25. A sufficiently decoupled system defines interfaces for each module. This ensures thatcomponents 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 morethan an adapter between endpoints and provides few merits of its own (Figure 1-3).Figure 1-3. Plumbing as a connector between core concernsPerhaps the worst characteristic of the integration layer is that it is notoriously difficultto test. Although Unit Tests, pieces of code that perform assertions on isolated func-tions, are quite easy to write given a properly designed module, Integration Tests aremuch 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 botha process prone to developer laziness (tests may not be written!) and increased time inthe build/test cycle.Plumbing is a means to an end, and therefore of little value in and of itself. It will benefitus to take an approach that minimizes the time we spend getting data from one endpointto another. As we’ll soon see, we may rely upon standards that remove this responsi-bility from our shoulders.Code Smart, Not HardThat’s a lot to consider before even a single line of code is written. Ironically, the sol-utions we concoct to address these issues are prone to becoming problems inthemselves, and we’re at risk for introducing a tangled mess.To state the obvious, the more that can be done for us, the less we have to do ourselves.6 | Chapter 1: Introduction
  26. 26. Do lessWhile it’s a likely requirement that business logic be unique to your application, themachinery that moves things along is not held to the same supposition. On the contrary,if aspects and plumbing are provided in a generic fashion, the developer is freed to limitboth scope and focus to more tangible requirements.Let’s say we want to register a new user with the system. Building everything in-houseusing traditional object-oriented methodology, we’d: 1. 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 talkabout pools and boundaries and databases is undermining the utility of a programminglanguage to help us express our ideas like humans. I’d much rather write: pseudofunction registerUser(user) { database.storeUser(user); mailService.emailUser(user); }If we could make the computational elements transparent, we’d be in position to paygreater attention to the business logic.The ContainerNow that we’ve identified candidates to be culled from our source tree, we may intro-duce an abstraction that provides the necessary features in a decoupled fashion. Acommonly employed technique is to take advantage of a construct called a Container.Loosely defined: A Container is a host that provides services to guest applications. The Problem Domain | 7
  27. 27. The intent here is to provide generic services upon which applications may rely. Theservice support desired is usually defined by some combination of user code andmetadata that together follow a contract for interaction between the application andcontainer. In the case of Enterprise JavaBeans (EJB) 3.1, this contract is provided by adocument jointly developed by experts under the authority of the Java CommunityProcess (http://jcp.org). Its job is to do all the work you shouldn’t be doing.The Enterprise JavaBeans™ 3.1 SpecificationJust as interfaces in code abstract the “what” from the “how,” the EJB Specificationdictates 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 concisemanner, alongside examples where appropriate.EJB definedLet’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 integratingmodules. Each component may represent a collection of business processes, and thesewill run centralized on the server (Figure 1-4).Additionally, the “distributed” nature will provide a mechanism to spread modulesacross 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 ofthe Java Enterprise Edition (http://java.sun.com/javaee/), such as messaging, transac-tions, resource management, persistence, and web services. It’s this integration thatwill reduce the evil plumbing we’d identified earlier.8 | Chapter 1: Introduction
  28. 28. Figure 1-4. Modules operating inside a runtime containerFigure 1-5. Using runtime containers to abstract the physical location of codeEmbracing the standard of EJB has other, nontechnical benefits. Applications that takeadvantage 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 SunMicrosystems “write once, run anywhere” philosophy of the Java language.Finally, the familiarity of EJB means that developers already oriented to the technologymay spend less time learning the control flow of a particular application, making hiringand training a much more simplified exercise. The Problem Domain | 9
  29. 29. ReviewWe’ve seen requirements common to many applications and how these can be metwithout recoding the same stuff the company across the street did last week. We’vediscussed 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-ownapproach.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 EditionThe specification offers a few different bean types, and the most sensible choice willdepend upon the intended purpose.10 | Chapter 1: Introduction
  30. 30. CHAPTER 2 Component TypesModeling real-life objects and concepts is one of the first skills a programmer mustdevelop. As such, we’ve become fairly adept at implementing object-oriented axiomssuch as reusability and extensibility on a daily basis. When we focus these principleson business logic, we end up with a set of business objects that encapsulate the rules ofthe road.Starting with the 3.0 version of the Specification, EJB imposes no API coupling orrestrictions upon the classes that will define our business objects. Commonly knownas POJO (Plain Old Java Object)* development, this means that an application devel-oper is under no obligation to extend, implement, or have any references tying theapplication to EJB. Now we can create class hierarchies however we see fit, and reuseour objects in some non-EJB environment (perhaps for quick testing outside of theContainer).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 ContainerThis is an important distinction. EJBs become such only in the context of the EJBContainer.The Container, in turn, is responsible for equipping POJOs with EJB Services (coveredin Chapter 3) as well as exposing their behavior via one of three personalities. We callthese personalities component types, and while implementing their semantics is beyondscope for an application developer, it’s important to know how, by contract, they’llbehave.We’ll use the example of a fictitious casino to showcase where each component typemight be applied.* Fowler et al. http://www.martinfowler.com/bliki/POJO.html 11
  31. 31. Server-Side Component TypesServer-side component types reside exclusively on the server, and the client must in-teract with them via some indirection. There are two major server-side componenttypes: session beans, which expose a view for the client to invoke upon, and message-driven beans, which act as event listeners.Session BeansIf EJB is a grammar, session beans are the verbs. They take action, and they frequentlycontain 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 asimple view the client may request of the EJB Container. This means that the clientdoes not access the EJB directly, which allows the Container to perform all sorts ofmagic before a request finally hits the target method. It’s this separation that allows forthe 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 thatwill 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 EJBContainerUltimately, it’s the bean instances created and managed by the Container that the serviceclient requests.Stateless session beans (SLSBs)Stateless session beans are useful for functions in which state does not need to be carriedfrom invocation to invocation. A client cannot assume that subsequent requests will12 | Chapter 2: Component Types
  32. 32. target any particular bean instance. In fact, the Container will often create and destroyinstances however it feels will be most efficient (see Figure 2-2). How a Containerchooses the target instance is left to the vendor’s discretion.Figure 2-2. An SLSB Instance Selector picking an instance at randomBecause there’s no rule linking an invocation to a particular target bean instance, theseinstances may be used interchangeably and shared by many clients. This allows theContainer to hold a much smaller number of objects in service, hence keeping memoryfootprint down.One caveat to beware: though a SLSB has stateless semantics, it’s backed by an instanceof a class created by the application developer. Particular care must be employed toassure that any shared members (instance variables, for instance) are not leaked be-tween invocations; this may lead to unpredictable behavior. We’ll explain this gotchawhen 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 implemen-tation choice. Roulette is a game with no memory—each spin operates independentlyfrom the last—so a function getSpinResult should return a random spot on the wheel.Stateful session beans (SFSBs)Stateful session beans differ from SLSBs in that every request upon a given proxy ref-erence is guaranteed to ultimately invoke upon the same bean instance. This is to say,SFSB invocations share conversational state. Each SFSB proxy object has an isolatedsession context, so calls to one session will not affect another.Stateful sessions, and their corresponding bean instances, are created sometime beforethe first invocation upon a proxy is made to its target instance (Figure 2-3). They liveuntil 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, thoughthe spec leaves this out-of-scope and up to the vendor). Server-Side Component Types | 13
  33. 33. Figure 2-3. Stateful session bean creating and using the correct client instance, which lives inside theEJB Container, to carry out the invocationIn order to minimize the number of stateful sessions carried around in memory, theContainer may passivate a SFSB bean instance. During passivation, the session’s stateis flushed to some persistent storage such that it may be removed from RAM. If thesession is needed again before it’s removed for good, the Container will activate it andbring the bean instance back into memory.No casino is complete without a good game of poker, and we could build ours usingSFSBs. Each game is played using a single deck, and we need to keep track of whichcards 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 couldensure that the integrity of the deck is intact.We’ll dive into SFSBs in Chapter 6.Singleton beansSometimes 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. Becauseall requests upon a singleton are destined for the same bean instance, the Containerdoesn’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 de-ployed; therefore, it may be leveraged to fire application lifecycle events. This draws arelationship where deploying a singleton bean implicitly leads to the invocation of itslifecycle callbacks. We’ll put this to good use when we discuss singleton beans inChapter 7.Dealers in a casino aren’t granted complete autonomy; they’ve got to clear a set ofprivileged 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 wemodel the boss as a singleton, all requests are passed along to the same source—one14 | Chapter 2: Component Types
  34. 34. Figure 2-4. Conceptual diagram of a singleton session bean with only one backing bean instanceable to make informed, consistent decisions. In addition, at the start of the pit boss’sshift, 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 communi-cate via a message describing a business event. EJB 3.1 interacts with messaging systemsvia 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 validsender. The message-driven bean, in turn, is a listener that consumes messages and mayeither handle them directly or delegate further processing to other EJB components.The asynchronous characteristic of this exchange means that a message sender is notwaiting 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 incomingeventsOne 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† EJB 3.1 Specification 5.4.17.1 Server-Side Component Types | 15
  35. 35. to a JMS Topic or Queue, an MDB may be created to take action upon that event. Byextension, any service with a valid JCA Resource Adapter may use MDB as an endpoint.We’ll untangle the various technologies that piece together asynchronous messagingin Chapter 8.Like SLSBs, MDBs have no conversational state. Any instance may be used in servicinga message. In fact, the client has no view or knowledge of the MDB at all! Once theclient sends a message, it’s out of scope to worry about what may be listening to theevent fired.After a full night of gambling, visitors to our casino are likely to need their cars backfrom the valet. We may provide our valet service via MDBs; once a ticket (message) isreceived, the valet should fetch the car while its owner continues on to grab a cup ofcoffee or visit the gift shop. The casino visitor will have to frequently check back to seewhether his car has arrived.Message-driven beans are explored in Chapter 8.Entity BeansWhile session beans are our verbs, entity beans are the nouns. Their aim is to expressan 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 managedobject only when associated with a construct called thejavax.persistence.EntityManager, a container-supplied service that tracks statechanges and synchronizes with the database as necessary. A client who alters the stateof 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 persistentstorage automatically upon invocation completion (Figure 2-6).Figure 2-6. Using an EntityManager to map between POJO object state and a persistent relationaldatabaseUnlike session beans and MDBs, entity beans are not themselves a server-side compo-nent type. Instead, they are a view that may be detached from management and used16 | Chapter 2: Component Types
  36. 36. just like any stateful object. When detached (disassociated from the EntityManager),there is no database association, but the object may later be re-enlisted with theEntityManager such that its state may again be synchronized. Just as session beans areEJBs only within the context of the Container, entity beans are managed only whenregistered with the EntityManager. In all other cases entity beans act as POJOs, makingthem extremely versatile.Users familiar with EJB 2.x forms may be used to the former notion of Container Man-aged Persistence (CMP), which required dependence upon a verbose API. Althoughentity bean classes were once required to implement specific interfaces and their call-back methods explicitly, these restrictions have been removed as of the 3.0 revision ofthe EJB Specification.Our casino exists primarily to move money. Taking bets, paying winners, makingchange—all are transactions that need to be recorded for bookkeeping purposes. Bymodeling currency as an entity bean, all functions that interact with cash and chipsmay share the same object view that ultimately will be preserved in the database forfuture auditing.Entity beans are introduced in Part III.The Java Persistence ModelThe sister to the EJB 3.1 Specification is the Java Persistence API (JPA) 2.0, developedin JSR-317 (http://jcp.org/en/jsr/detail?id=317). EJBs may become equipped with thefacilities defined by JPA, such that modifying the properties of a managed object willbe reflected automatically in the backing database. In addition to support within EJB,JPA may be used in standalone Java Standard Edition (SE) environments.Persistence is simply a higher-level abstraction above Java Database Connectivity(JDBC). By exposing the database as objects to the developer, backing rows may bequeried, loaded, updated, or removed without explicitly having to go through a con-tracted API or language such as SQL. In older versions of EJB, persistence was part ofthe specification, but starting with EJB 3.0, it has been spun off on its own. The entitybean is EJB’s integration with JPA, and it is defined by enhancing a plain class definitionwith some additional persistence metadata.The Model Isn’t EverythingThe various EJB Component types allow stateful, stateless, asynchronous, and persis-tent logic to be easily modeled. Now it’s time to see how they’ll shine under the brightlights of Container services. The Model Isn’t Everything | 17
  37. 37. CHAPTER 3 Container ServicesWe see examples of efficient processes every day, even in our most mundane dailyroutines. A trip to the supermarket may involve ordering sliced meats from the delicounter, selecting grocery items from pre-stacked shelves, listening to advice from thebutcher, and paying the cashier. If we were to model this errand as a business system,we’d notice that the whole is composed of many smaller pieces, and each task is servicedby a specialized worker. It is this same “do one thing and do it well”* approach thatwas introduced in French firearms production, powered the assembly lines pioneeredby Henry Ford, and became omnipresent during the American industrial revolution asthe preferred mechanism to maximize throughput.The benefits of allowing each concern to be fulfilled by a specialist through division oflabor are fairly obvious: a secretary should answer phones while a mail room attendanthandles shipping. Similarly, application developers should write the rules of their busi-ness and leave the mechanics of reliable, distributed systems to middleware providers.In the case of EJB, the Component Model defines our interchangeable parts, and theContainer Services are specialists that perform work upon them. The Specificationprovides: • Dependency injection • Concurrency • Instance pooling/caching • Transactions • Security • Timers • Naming and object stores • Interoperability • Lifecycle callbacks* Doug McIlroy, Basics of the Unix Philosophy, http://www.faqs.org/docs/artu/ch01s06.html 19
  38. 38. • Interceptors • Java Enterprise Platform integrationWe’ll introduce each at a high level here, and get into further detail later (Part III).Dependency Injection (DI)A component-based approach to software design brings with it the complication ofinter-module communication. Tightly coupling discrete units together violates moduleindependence and separation of concerns, while using common lookup code leads tothe maintenance of more plumbing. Martin Fowler details this problem in his paper“Inversion of Control Containers and the Dependency Injection Pattern,” which hasspurred the development and success of many popular standalone DI containers.†As EJB is a component-centric architecture, it provides a means to reference dependentmodules in decoupled fashion. The end result is that you’ll adhere to a contract and letthe container provide the implementation at deployment time.In pseudocode, this looks like: prototype UserModule { // Instance Member @DependentModule MailModule mail; // A function function mailUser() { mail.sendMail("me@ejb.somedomain"); } }The fictitious @DependentModule annotation serves two purposes: • Defines a dependency upon some service of type MailModule. UserModule may not deploy until this dependency is satisfied. • Marks the instance member mail as a candidate for injection. The container will populate this field during deployment.Dependency injection encourages coding to interfaces, and not to any particular im-plementation; we’ll see it in action in Chapter 16.† http://martinfowler.com/articles/injection.html20 | Chapter 3: Container Services
  39. 39. ConcurrencyAssuming each Service is represented by one instance, dependency injection alone is afine solution for a single-threaded application; only one client may be accessing a re-source at a given time. However, this quickly becomes a problem in situations wherea centralized server is fit to serve many simultaneous requests. Deadlocks, livelocks,and race conditions are some of the possible nightmares arising out of an environmentin which threads may compete for shared resources. These are hard to anticipate, harderto debug, and are prone to first exposing themselves in production! Proper solutionslie outside the scope of this book,‡ and for good reason: EJB allows the applicationdeveloper to sidestep the problem entirely thanks to a series of concurrency policies.That said, there are a series of effects upon performance to consider, so the specificationallows for configuration in some cases. Otherwise, it’s important to be aware how eachcomponent type views concurrency concerns; this is covered alongside the session beanin Chapters 5, 6, and 7.Instance Pooling/CachingBecause of the strict concurrency rules enforced by the Container, an intentionalbottleneck is often introduced where a service instance may not be available for pro-cessing until some other request has completed. If the service was restricted to a singularinstance, all subsequent requests would have to queue up until their turn was reached(see Figure 3-1).Figure 3-1. Client requests queuing for service‡ Recommended reading is Java Concurrency in Practice, Goetz et al., http://www.javaconcurrencyinpractice .com/ Instance Pooling/Caching | 21
  40. 40. Conversely, if the service was permitted to use any number of underlying instances,there would be no guard to say how many requests could be processed in tandem, andaccess across the physical machine could crawl to a halt as its resources were spreadtoo thin (Figure 3-2).Figure 3-2. Many invocations executing concurrently with no queuing policyEJB addresses this problem through a technique called instance pooling, in which eachmodule is allocated some number of instances with which to serve incoming requests(Figure 3-3). Many vendors provide configuration options that allow the deployer toallocate pool sizes appropriate to the work being performed, providing the compromiseneeded to achieve optimal throughput.Figure 3-3. A hybrid approach using a poolInstance pooling addresses performance, and it is explained alongside session beans inChapters 5, 6, and 7.22 | Chapter 3: Container Services
  41. 41. TransactionsAs a routine chugs along, it may perform half of its duties before encountering someexceptional circumstance that prevents successful completion. At this point, the systemmay be left in an unreliable or incorrect state. Take the popular “account transferexample”: 1. User requests that $100 be transferred between her checking and savings accounts. 2. System deducts $100 from checking. 3. An unexpected error is thrown up the call chain.The money has disappeared from record, and the customer is out $100. Although thismay be a desirable scenario if you’re a particularly scheming bank manager, in mostcases we’d like our programs to reliably leave things in consistent state. EJB ensuresthis via its integration with the Java Transaction Service (JTS; http://java.sun.com/javaee/technologies/jts/) and exposes an API that gives the bean provider (application de-veloper) control over the properties specifying how a transaction-aware applicationbehaves. Again, the nuts and bolts of how this is achieved is not a problem for the EJBdeveloper; all that’s required is some understanding of the ACID§ fundamentals:Atomicity Every instruction in a call completes or none do. If there’s a failure halfway through, state is restored to the point before the request was made.Consistency The system will be consistent with its governing rules both before and after the request.Isolation Transactions in progress are not seen outside the scope of their request until suc- cessful completion. Shared resources may not be mutated by two transactions at once.Durability Once a transaction successfully returns, it must commit to its changes. The system must process the result once a client has received word of normal completion.There are a variety of options available to configure transactional behavior, and theseare explored in Chapter 17.SecurityMultiuser applications are likely to expose a wide variety of operations, and not allcallers are created equal. An unsecured banking system won’t discriminate between a§ An acronym coined by Andreas Reuter and Theo Haerder in 1983, “Principles of Transaction-Oriented Database Recovery” Security | 23
  42. 42. teller and a branch manager when confronted with a request to approve a loan, andmanually baking this logic into the business method mixes two concerns. EJB thereforeprovides a role-based security mechanism that bolsters existing application code witha set of security policies governed by the Container (Figure 3-4).Figure 3-4. EJB Security permitting access based upon the caller’s roleThis allows the application developer to explicitly allow or deny access at a fine-grainedlevel based upon the caller’s identity.We’ll delve into the security model in Chapter 15.TimersSo far, we’ve dealt exclusively with client-initiated requests. While this may handle thebulk of an application’s requirements, it doesn’t account for scheduled jobs: • A ticket purchasing system must release unclaimed tickets after some timeout of inactivity. • An auction house must end auctions on time. • A cellular provider should close and mail statements each month.The EJB Timer Service may be leveraged to trigger these events and has been enhancedin the 3.1 specification with a natural-language expression syntax.We play with timers in Chapter 19.Naming and Object StoresAll naming services essentially do the same thing: they provide clients with a mechanismfor locating distributed objects or resources. To accomplish this, a naming service must24 | Chapter 3: Container Services

×