text:
Utama EJB 3 in Action, 2nd Edition
You can write a book review and share your experiences. Other readers will always be interested in your opinion of the books you've read. Whether you've loved the book or not, if you give your honest and detailed thoughts then people will find new books that are right for them.
MANNING SECOND EDITION Debu Panda Reza Rahman Ryan Cuprak Michael Remijan www.it-ebooks.info Praise for the First Edition This is the EJB book to read! Don't miss its practical advice. —Jeanne Boyarsky, JavaRanch.com A technical book that is surprisingly entertaining. —King Y. Wang, Oracle Canada Great book—covers everything relating to EJB 3. —Awais Bajwa, Expert Group Member JSR 243 Java Data Objects Well-written, easy, and fun. —Patrick Dennis, Management Dynamics Inc. Written with a wide audience in mind … not just a recitation of the EJB specification … includes a lot of practical advice. Has a light, humorous, and accessible style of writing and all the concepts are illustrated with examples. —One Minute Review from javalobby.org Broad coverage of EJB 3 with a very simple and excellently crafted case study. The book starts lightly on this complex subject and slowly dives into the details of advanced concepts like interceptors, transactions, security, JPA, and performance issues, developing each scenario in the case study. Overall, a very good book and a very smooth read. —Amazon.com reader www.it-ebooks.info www.it-ebooks.info EJB 3 in Action Second Edition DEBU PANDA REZA RAHMAN RYAN CUPRAK MICHAEL REMIJAN MANNING SHELTER ISLAND www.it-ebooks.info For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: firstname.lastname@example.com ©2014 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations app; ear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning's policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Development editor: Copyeditor and project editor: Proofreaders: Technical proofreader: Typesetter: Cover designer: ISBN: 9781935182993 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 19 18 17 16 15 14 www.it-ebooks.info Nermina Miller Jodie Allen Linda Recktenwald, Melody Dolab Deepak Vohra Dennis Dalinnik Marija Tudor brief contents PART 1 PART 2 PART 3 OVERVIEW OF THE EJB LANDSCAPE . ..............................1 1 ■ What's what in EJB 3 2 ■ A first taste of EJB 3 25 WORKING WITH EJB COMPONENTS ..............................47 3 ■ Building business logic with session beans 49 4 ■ Messaging and developing MDBs 93 5 ■ EJB runtime context, dependency injection, and crosscutting logic 117 6 ■ Transactions and security 7 ■ Scheduling and timers 196 8 ■ Exposing EJBs as web services 160 214 USING EJB WITH JPA AND CDI .................................251 9 ■ JPA entities 253 10 ■ Managing entities 294 11 ■ JPQL 321 12 ■ Using CDI with EJB 3 359 v www.it-ebooks.info vi PART 4 BRIEF CONTENTS PUTTING EJB INTO ACTION .......................................395 13 ■ Packaging EJB 3 applications 397 14 ■ Using WebSockets with EJB 3 427 15 ■ Testing and EJB 458 www.it-ebooks.info contents preface xv acknowledgments xvii about this book xx about the authors xxiv about the cover illustration xxvi PART 1 OVERVIEW OF THE EJB LANDSCAPE . ..................1 1 What's what in EJB 3 3 1.1 EJB overview 4 EJB as a component model 5 EJB component services 5 Layered architectures and EJB 7 Why choose EJB 3? 9 ■ ■ 1.2 Understanding EJB types 11 Session beans 11 1.3 ■ Message-driven beans Related specifications 12 Entities and the Java Persistence API 12 dependency injection for Java EE 13 1.4 EJB runtimes 12 ■ Contexts and 14 Application servers 14 EJB Lite 15 Embeddable containers 16 Using EJB 3 in Tomcat 16 ■ ■ vii www.it-ebooks.info ■ CONTENTS viii 1.5 Brave new innovations 17 "Hello User" example 17 Annotations versus XML 18 Intelligent defaults versus explicit configuration 19 Dependency injection versus JNDI lookup 19 CDI versus EJB injection 20 Testable POJO components 20 ■ ■ ■ 1.6 Changes in EJB 3.2 21 Previous EJB 2 features now optional 21 Enhancements to message-driven beans 21 Enhancements to stateful session beans 22 Simplifying local interfaces for stateless beans 23 Enhancements in TimerService API 23 Enhancements in EJBContainer API 23 EJB API groups 23 ■ ■ ■ ■ ■ 1.7 2 Summary 24 A first taste of EJB 25 2.1 Introducing the ActionBazaar application Starting with the architecture 2.2 27 Using CDI with EJB 3 ■ 29 Using stateful beans Using JPA 2 with EJB 3 ■ Using CDI with EJB 3 41 Mapping JPA 2 entities to the database 42 EntityManager 44 2.5 31 37 Using CDI with JSF 2 and EJB 3 37 and JPA 2 40 2.4 26 An EJB 3–based solution 28 Building business logic with EJB 3 Using stateless session beans 29 Unit testing EJB 3 36 2.3 ■ ■ Using the Summary 45 PART 2 WORKING WITH EJB COMPONENTS ..................47 3 Building business logic with session beans 49 3.1 Getting to know session beans When to use session beans session bean types 52 3.2 Stateless session beans 51 ■ 50 Component state and 55 When to use stateless session beans 55 Stateless session bean pooling 56 BidService example 57 Using the @Stateless annotation 60 Bean business interfaces 60 Lifecycle callbacks 63 Using stateless session beans effectively 65 ■ ■ ■ ■ ■ www.it-ebooks.info CONTENTS 3.3 Stateful session beans ix 66 When to use stateful session beans 67 Stateful session bean passivation 68 Stateful session bean clustering 68 Bidder account creator bean example 69 Using the @Stateful annotation 72 Bean business interfaces 72 Lifecycle callbacks 73 Using stateful session beans effectively 75 ■ ■ ■ ■ ■ ■ 3.4 Singleton session beans 76 When to use singleton session beans 76 ActionBazaar featured item example 78 Using the @Singleton annotation 79 Singleton bean concurrency control 80 Bean business interface 83 Lifecycle callbacks 83 @Startup annotation 85 Using stateful singleton session beans effectively 85 ■ ■ ■ ■ 3.5 ■ Asynchronous session beans 87 Basics of asynchronous invocation 87 When to use asynchronous session beans 88 ProcessOrder bean example 88 Using the @Asynchronous annotation 90 Using the Future interface 91 Using asynchronous session beans effectively 91 ■ ■ ■ ■ 3.6 4 Summary 92 Messaging and developing MDBs 4.1 Messaging concepts 93 94 Message-oriented middleware 94 Messaging in ActionBazaar 95 Messaging models 97 ■ ■ 4.2 Introducing JMS 99 JMS Message interface 100 4.3 Working with MDBs 102 When to use messaging and MDBs 103 Why use MDBs? 103 Developing a message consumer with MDB 104 Using the @MessageDriven annotation 106 Implementing the MessageListener 106 Using ActivationConfigProperty 107 Using bean lifecycle callbacks 110 Sending JMS messages from MDBs 112 Managing MDB transactions 113 ■ ■ ■ ■ ■ ■ 4.4 4.5 5 MDB best practices Summary 115 113 EJB runtime context, dependency injection, and crosscutting logic 117 5.1 EJB context 118 Basics of EJB context 118 EJB context interfaces 119 Accessing the container environment through the EJB context 120 ■ www.it-ebooks.info CONTENTS x 5.2 Using EJB DI and JNDI 121 JNDI primer for EJB 122 How EJB names are assigned 125 EJB injection using @EJB 128 When to use EJB injection 129 @EJB annotation in action 129 Resource injection using @Resource 132 When to use resource injection 133 @Resource annotation in action 133 Looking up resources and EJBs from JNDI 137 When to use JNDI lookups 138 Application client containers 138 Embedded containers 139 Using EJB injection and lookup effectively 141 EJB versus CDI injection 141 ■ ■ ■ ■ ■ ■ ■ ■ 5.3 AOP in the EJB world: interceptors 142 What is AOP? 143 Interceptor basics 143 When to use interceptors 144 How interceptors are implemented 144 Specifying interceptors 145 Interceptors in action 148 Using interceptors effectively 154 CDI versus EJB interceptors 154 ■ ■ ■ ■ ■ 5.4 6 Summary 159 Transactions and security 160 6.1 Understanding transactions 161 Transaction basics 162 Transactions in Java 164 Transactions in EJB 165 When to use transactions 167 How EJB transactions are implemented 167 Two-phase commit 169 JTA performance 170 ■ ■ ■ 6.2 Container-managed transactions 171 Snag-it ordering using CMT 171 @TransactionManagement annotation 172 @TransactionAttribute annotation 172 Marking a CMT for rollback 176 Transaction and exception handling 177 Session synchronization 179 Using CMT effectively 179 ■ ■ ■ ■ 6.3 Bean-managed transactions 180 Snag-it ordering using BMT 181 Getting a UserTransaction 181 Using user transactions 182 Using BMT effectively 184 ■ ■ 6.4 EJB security 185 Authentication versus authorization 185 User, groups, and roles 186 How EJB security is implemented 186 EJB declarative security 190 EJB programmatic security Using EJB security effectively 194 ■ ■ ■ 6.5 Summary 195 www.it-ebooks.info 192 CONTENTS 7 xi Scheduling and timers 196 7.1 Scheduling basics 197 Timer Service features Timer interface 200 7.2 Declarative timers 197 Time-outs 199 Types of timers 202 ■ ■ ■ Cron 199 202 @Schedule annotation 203 @Schedules annotation 203 @Schedule configuration parameters 204 Declarative timer example 204 Cron syntax rules 206 ■ ■ ■ 7.3 Using programmatic timers 208 Understanding programmatic timers 208 Programmatic timer example 210 Using EJB programmatic timers effectively 211 ■ ■ 7.4 8 Summary 212 Exposing EJBs as web services 214 8.1 What is a web service? 215 Web service properties 215 Transports 216 Web service types 216 Java EE web service APIs Web services and JSF 217 ■ ■ 8.2 Exposing EJBs using SOAP (JAX-WS) 217 217 Basics of SOAP 218 When to use SOAP web services 222 When to expose EJBs as SOAP web services 222 SOAP web service for ActionBazaar 223 JAX-WS annotations 227 Using EJB SOAP web services effectively 231 ■ ■ ■ 8.3 Exposing EJBs using REST (JAX-RS) 233 Basics of REST 233 When to use REST/JAX-RS 236 When to expose EJBs as REST web services 237 REST web service for ActionBazaar 238 JAX-RS annotations 241 Using EJB and REST web services effectively 246 ■ ■ ■ 8.4 8.5 Choosing between SOAP and REST 247 Summary 248 PART 3 USING EJB WITH JPA AND CDI......................251 9 JPA entities 253 9.1 Introducing JPA 254 Impedance mismatch 254 and JPA 255 9.2 Domain modeling ■ Relationship between EJB 3 256 Introducing domain models 256 domain model 256 www.it-ebooks.info ■ ActionBazaar CONTENTS xii 9.3 Implementing domain objects with JPA 260 @Entity annotation 260 Specifying the table 261 Mapping the columns 265 Temporal types 269 Enumerated types 269 Collections 270 Specifying entity identity 272 Generating primary keys ■ ■ ■ ■ 9.4 Entity relationships 277 281 One-to-one relationships 281 One-to-many and many-to-one relationships 283 Many-to-many relationships 285 ■ ■ 9.5 Mapping inheritance 287 Single-table strategy 288 Joined-tables strategy Table-per-class strategy 290 ■ 9.6 10 289 Summary 292 Managing entities 294 10.1 Introducing EntityManager 295 EntityManager interface 295 Lifecycle of an entity 297 Persistence context, scopes, and the EntityManager 300 Using EntityManager in ActionBazaar 302 Injecting the EntityManager 302 Injecting the EntityManagerFactory 305 ■ ■ ■ 10.2 Persistence operations 306 Persisting entities 307 Updating entities 313 10.3 Entity queries 11 Summary ■ 308 317 Dynamic queries 318 10.4 Retrieving entities by key Deleting entities 316 ■ Named queries 318 ■ 319 JPQL 321 11.1 Introducing JPQL 322 Statement types 322 SELECT clause 334 Joining entities 338 11.2 Criteria queries ■ ■ ■ FROM clause 324 Ordering results 336 Bulk updates and deletes 340 340 Meta-model API 341 CriteriaBuilder 344 CriteriaQuery 345 Query root 346 FROM clause 349 SELECT clause 349 ■ ■ 11.3 ■ Native queries 352 Using dynamic queries with native SQL 353 Using a named native SQL query 353 Using stored procedures 355 ■ ■ 11.4 Summary 357 www.it-ebooks.info CONTENTS 12 xiii Using CDI with EJB 3 359 12.1 Introducing CDI 360 CDI services 361 Relationship between CDI and EJB 3 364 Relationship between CDI and JSF 2 365 ■ 12.2 CDI beans 365 How to use CDI beans 366 Component naming and EL resolution 366 Bean scoping 368 ■ ■ 12.3 Next generation of dependency injection 370 Injection with @Inject 370 Producer methods 372 Using qualifiers 374 Disposer methods 375 Specifying alternatives 376 ■ ■ 12.4 Interceptor and decorators Interceptor bindings 12.5 12.6 12.7 12.8 12.9 378 ■ 378 Decorators 381 Component stereotypes 382 Injecting events 383 Using conversations 386 Using CDI effectively with EJB 3 Summary 392 391 PART 4 PUTTING EJB INTO ACTION ...........................395 13 Packaging EJB 3 applications 13.1 397 Packaging your applications 398 Dissecting the Java EE module system EE module 401 13.2 400 ■ Loading a Java Exploring class loading 403 Class-loading basics 403 Class loading in Java EE applications 404 Dependencies between Java EE modules 404 ■ ■ 13.3 Packaging session and message-driven beans 407 Packaging EJB-JAR 407 Packaging EJB in WAR 409 XML versus annotations 412 Overriding annotations with XML 415 Specifying default interceptors 416 ■ ■ ■ 13.4 JPA packaging 417 Persistence module 417 Describing the persistence module with persistence.xml 419 ■ 13.5 CDI packaging 420 CDI modules 421 Using the beans.xml deployment descriptor 421 Using the bean-discovery-mode annotation ■ ■ www.it-ebooks.info 422 CONTENTS xiv 13.6 Best practices and common deployment issues Packaging and deployment best practices common deployment problems 425 13.7 14 Summary 423 ■ 423 Troubleshooting 426 Using WebSockets with EJB 3 427 14.1 14.2 Limits of request–response 427 Introducing WebSockets 429 WebSockets basics 429 WebSockets versus Comet 14.3 ■ WebSockets versus AJAX 432 434 WebSockets and Java EE 435 WebSocket endpoints 436 Session interface 437 Decoders and encoders 440 ■ 14.4 WebSockets in ActionBazaar 442 Using programmatic endpoints 445 Using annotated endpoints 448 14.5 14.6 15 Using WebSockets effectively Summary 456 454 Testing and EJB 458 15.1 Introducing testing Testing strategies 15.2 15.3 459 Unit testing EJBs 461 Integration testing using embedded EJBContainer Project configuration 15.4 appendix A appendix B appendix C 465 ■ Integration test Integration testing using Arquillian Project configuration 15.5 15.6 459 Testing effectively Summary 478 471 ■ 470 Integration test 477 Deployment descriptor reference 480 Getting started with Java EE 7 SDK 489 EJB 3 developer certification exam 503 index 511 www.it-ebooks.info 467 474 464 preface In its early days, EJB was inspired by the distributed computing ideas of technologies such as CORBA and was intended to add scalability to server-side applications. EJB and J2EE enjoyed some of the greatest buzz in the industry during the dot.com boom. The initial goal for EJB was to provide a simpler alternative to CORBA through the benefits of a standard development framework and reusable components. By the time EJB 2 was released, it became apparent that the EJB framework could become the new standard for server-side development. The framework provided Enterprise developers with everything they needed—remoting, transaction management, security, state maintenance, persistence, and web services—but it was heavyweight, requiring developers to focus more on the framework itself than on the requirements of their business applications. Because EJB was loaded with more features, its inventors failed to address its growing complexity. As the community became disenchanted with the limitations of EJB 2, innovative open source tools emerged. These tools were signs of the increasing discontent with the complexities of Java EE. Though well-intentioned, these tools made Enterprise development even more complex since they deviated from the standards of the application server they were to run in. It was time for the Java Community Process (JCP) and expert groups to work on the simplification of Java EE development. That was the sole motivation behind Java EE 5 and the goal of the EJB 3 expert group. For a technology with a wide deployment base, the changes that came with EJB 3 were nothing short of stunning. EJB 3 successfully melds innovative techniques to make component development as easy as possible. These techniques include the use xv www.it-ebooks.info xvi PREFACE of annotations, metadata programming, dependency injection, AspectJ-like interceptors, and intelligent defaulting. The heavyweight inheritance-based programming model was abandoned in favor of Plain Old Java Object (POJO) programming, and the verbose XML descriptor was now out of the developer's way. The changes to the persistence model were particularly dramatic. EJB 3 left behind the flawed EJB 2 Entity Beans model in favor of the lightweight Java Persistence API (JPA). Unlike Entity Beans, JPA is not container-based. It has more in common with open source object relational mapping (ORM) tools that emerged in the community in response to Entity Beans complexity. JPA can be used either inside or outside a Java Enterprise server and is now the de facto persistence standard for Java. Its Java Persistence Query Language (JPQL) standardizes object relational queries but also supports native SQL queries if the need arises. The changes made in EJB 3 have been well received in the Java community. Its simplified specification has led to its wide adoption in new projects. More and more companies are giving the once "ugly" EJB technology another look and they like what they see. With the release of EJB 3.2, the adoption will continue to grow. EJB 3.2 has made support for EJB 2 optional so that older technology can finally be sunset and innovations in EJB 3 can continue to grow. EJB 3.2 has also seen major enhancements to message-driven beans (MDBs), making messaging much easier. EJB 3.2 made improvements to stateful session bean passivation and session bean local interfaces, as well as dramatic improvements to the timer services. All this and more await you in EJB 3.2. Since EJB is POJO-based, every Java developer can easily become an EJB developer. Simple annotations give your business logic safe transaction management, security, and exposure as web services for easy interoperability in your company. We strive to keep our book different from other books on EJB by providing practical examples, best practices, and tips for performance tuning. We highlight what's new in the EJB 3.2 specification, which gives you more tools for your development. We hope this revised edition will help you to quickly learn how to use EJB 3 effectively in your next Enterprise application. www.it-ebooks.info acknowledgments Authoring a book requires great effort and it's difficult to list everyone who helped us during this project. First and foremost we'd like to thank everyone at Manning for their encouragement and support, especially publisher Marjan Bace, associate publisher Michael Stephens, and our editor Nermina Miller. We'd also like to thank others at Manning who worked on different stages of the project: review editor Olivia Booth; project editor Jodie Allen; development manager Maureen Spencer; technical proofreader Deepak Vohra, who performed a final review of the book shortly before it went to press; Linda Recktenwald and Melody Dolab, who edited, proofread, and polished our prose; and typesetter Dennis Dalinnik, who converted our Word documents into a real book! Thanks also to all of those who worked behind the scenes to help get our book published. Many reviewers spent their valuable time reading the manuscript at various stages of its development, and their feedback greatly improved the quality of the book. We'd like to thank Artur Nowak, Aziz Rahman, Bob Casazza, Christophe Martini, David Strong, Jeet Marwah, John Griffin, Jonas Bandi, Josef Lehner, Jürgen De Commer, Karan Malhi, Khalid Muktar, Koray Güclü, Luis Peña, Matthias Agethle, Palak Mathur, Pavel Rozenblioum, Rick Wagner, Sumit Pal, Victor Aguilar, Wellington Pinheiro, and Zorodzayi Mukuya. Finally, thanks to the readers of Manning's Early Access Program (MEAP), who read our chapters as they were being written and posted comments and corrections in the book's online forum. Your input has made this a better book. xvii www.it-ebooks.info ACKNOWLEDGMENTS xviii DEBU PANDA I'd like to thank my wife, Renuka, for her immense support and continuous encouragement and for her patience with all the late nights, early mornings, and weekends that I spent on the first edition of the book. I'd also like to thank my kids, Nistha and Nisheet, who had to share their bapa with the computer during that time. Many thanks to my coauthors Reza Rahman, Ryan Cuprak, and Michael Remijan, who worked hard on the second edition of the book. REZA RAHMAN A journey of a thousand miles begins with a single step. —Lao-tzu When I decided to take on writing the first edition of this book, I don't think any of the authors were certain how successful the book was going to be or where it might take us personally. Today I have the luxury of hindsight in saying the book has been a resounding success and that writing it was the first step of a whirlwind journey over the past few years that I could have never foreseen. I must confess I continue to enjoy every minute of it. Since finishing the first edition, I've become increasingly more engaged with the Java community. I've contributed to various Java EE expert groups, including the EJB expert group, had the once-in-a-lifetime opportunity to write an open source EJB container almost from scratch, and now find myself at the forefront of the Java EE evangelism team at SunOracle. One casualty of all of this has been my own personal bandwidth, which was more abundant when I wrote the first edition. This is a large part of why we had to skip a Java EE 6 and EJB 3.1 edition of this book. I do think it's all for the best since Java EE 7 is an even stronger and more compelling platform, as this edition will demonstrate. I'm extremely grateful to Michael and Ryan for taking ownership of the book and being instrumental in producing a worthy second edition. I'm also grateful to the many folks like you in the Java EE community that I've had the privilege to serve and work with. Lastly, I'm ever thankful to my wife Nicole and daughter Zehra for allowing me to pursue my passion without reservation. And so the journey continues. RYAN CUPRAK Writing this book would not have been possible without the support of family and friends. I'd especially like to thank the love of my life, Elsa, who has supported and encouraged me throughout the long, arduous process and the many long nights I was hunched over the computer. Finally, I'd like to thank Reza for recruiting me to this project and encouraging me to take a second look at Java EE many years ago. MICHAEL REMIJAN My wonderful wife Kelly and my daughter Sophia are the first people I need to thank when it comes to writing this book. It's one of many adventures we've shared together, www.it-ebooks.info ACKNOWLEDGMENTS xix and without their support while I worked early mornings, late nights, and weekends, I wouldn't have been able to do the research and writing necessary for a project this big. Kelly is my best friend, who encourages me in all I do, and is the perfect one for me—I love her dearly. I'm blessed with a remarkable family. My coauthors Debu, Ryan, and Reza are next, and many thanks go to them. This book was a team effort. EJB is a great technology with many, many features; hence the size of this book. It'd be a monumental task for one person to write it on their own, so the collaboration among us was essential for delivering this book. It was a great opportunity to work with such talented colleagues. Finally, thanks to all the people at Manning who did countless reviews and kept the book on track, especially Maureen Spencer and Jodie Allen. Christina Rudloff originally recruited me into the project, and without her I wouldn't have gotten involved. www.it-ebooks.info about this book EJB 3 is meant to recast Java server-side development into a mold you might not expect. Therefore, we've tried to make this an EJB book you might not anticipate. Most server-side Java books tend to be serious affairs—heavy on theory, slightly preachy, and geared toward the advanced developer. While we easily fit the stereotype of geeks and aren't the funniest comedians or entertainers, we've tried to add some color to our writing to keep this book as lighthearted and down-to-earth as possible. The tone is intended to be friendly, conversational, and informal. We made a conscious effort to drive the chapter content with examples that are close to the realworld problems you deal with every day. In most cases, we introduce a problem that needs to be solved, show you the code to solve it using EJB 3, and explore features of the technology using the code. We cover theory when it is necessary. We try to avoid theory for theory's sake and to make the discussion as lively as we can. The goal of this book is to help you learn EJB 3 quickly and effectively, not to be a comprehensive reference book. We don't cover features you're unlikely to use. Instead, we provide deep coverage of the most useful EJB 3 features and its related technologies. We discuss various options so you can make educated choices, warn you about common pitfalls, and tell you about battlehardened best practices. If you've picked up this book, it's unlikely you're a complete newcomer to Java. We assume you've done some work in Java, perhaps in the form of web development using a presentation-tier technology like JSF, Struts, JSP, or Servlets. We assume you're familiar with database technologies such as JDBC and have at least a casual familiarity xx www.it-ebooks.info ABOUT THIS BOOK xxi with SQL. You don't need any experience with EJB 2.x to pick up this book; EJB 3 is completely new. We don't assume you know any of the Java EE technologies that EJB is dependent on, such as the Java Naming and Directory Interface (JNDI), Java Remote Method Invocation (RMI), and Java Messaging Service (JMS). In fact, we assume you're not familiar with middleware concepts like remoting, pooling, concurrent programming, security, and distributed transactions. This book is ideally suited for a Java developer with a couple of years' experience who is curious about EJB 3. You might find this book different from others in one more important way. EJB is a server-side middleware technology. This means that it doesn't live in a vacuum and must be integrated with other technologies to fulfill its mission. Throughout the book, we talk about how EJB 3 integrates with technologies like JNDI, JMS, JSF, JSP, Servlets, AJAX, and even Swing-based Java SE clients. This book is about EJB 3 as a standard, not a specific application server technology. For this reason, we avoid tying our discussion to any specific application server implementation. Instead, the code samples in this book are designed to run with any EJB 3 container or persistence provider. The website accompanying this book at www.manning.com/EJB3inActionSecondEdition will tell you how you can get the code up and running in GlassFish and Oracle Application Server 10g. Maintaining the application server–specific instructions on the publisher's website instead of in the book will allow us to keep the instructions up to-date with the newest implementation details. Roadmap This book is divided into four parts. Part 1 provides an overview of EJB. Chapter 1 introduces EJB 3 and EJB types, makes the case for EJB 3, and provides an overview of changes introduced with EJB 3.2. Chapter 2 gives you a first taste of EJB, building EJB as you build your first solution using EJB technology. Part 2 covers working with EJB components to implement your business logic. Chapter 3 dives into the details of session beans and outlines best practices. Chapter 4 gives a quick introduction to messaging and JMS and covers MDB in detail. Chapter 5 covers advanced topics such as the EJB context, JNDI, resource and EJB injection, AOP interceptors, and the application client container. Chapter 6 discusses transaction and security. Chapter 7 introduces timers and new scheduling options. Chapter 8 exposes EJB business logic as SOAP and RESTful web services. Part 3 provides in-depth coverage of EJB 3's relationship with JPA and CDI. Chapter 9 introduces domain modeling and how to map JPA entities to your domain. Chapter 10 covers managing JPA entities through CRUD operations. Chapter 11 introduces JPQL and covers retrieval of data in-depth. Chapter 12 is an introduction to CDI and how it complements EJB development. Part 4 provides guidelines for putting EJB 3 into action in your enterprise. Chapter 13 discusses packaging EJBs and entities for deployment to a server. Chapter 14 www.it-ebooks.info ABOUT THIS BOOK xxii introduces web sockets, their relationship to EJBs, and asynchronous business logic execution using the EJB concurrency utilities. Chapter 15 covers unit and integration testing without the need for deployment to a running server. The book has three appendixes. Appendix A is a reference on the ejb-jar.xml deployment descriptor. Appendix B contains step-by-step instructions on downloading and installing the Java EE 7 SDK, which includes Java SE 7, GlassFish 4, and NetBeans. Appendix C provides information on Oracle's EJB certification process and the EJB certification exam. Source code downloads Appendix B provides step-by-step instructions on installation of the Java EE 7 SDK. The source code for this book is available from http://code.google.com/p/action-bazaar/. From here you can either clone the Git repository to get a copy of all of the examples or you can download a prepared ZIP file that has all the code in it. The code was developed primarily in NetBeans, but all the examples are built with Maven, so they should run in your favorite IDE. A zip file with the source code is also available for download from the publisher's website at www.manning.com/EJB3inActionSecondEdition. Source code conventions Because of the example-driven style of this book, the source code was given a great deal of attention. Larger sections of code in the chapters are presented as their own listings. All code is formatted using fixed-width Courier font like this for visibility. All inside code, such as XML element names, method names, Java type names, package names, variable names, and so on, are also formatted using Courier font. Some code is formatted as Courier Bold to highlight important sections. Code annotations are also sometimes used to point out important concepts. In some cases, we've abbreviated the code to keep it short and simple. In all cases, the full version of the abbreviated code is contained in the downloadable zip files. We encourage you to set up your development environment for each chapter before you begin reading it. Author Online Purchase of EJB 3 in Action, Second Edition includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the authors and other users. To access the forum and subscribe to it, point your web browser to www.manning.com/ EJB3inActionSecondEdition. This Author Online (AO) page provides information on how to get on the forum once you're registered, what kind of help is available, and the rules of conduct on the forum. Manning's commitment to our readers is to provide a venue where a meaningful dialog among individual readers and between readers and the authors can take place. www.it-ebooks.info ABOUT THIS BOOK xxiii It's not a commitment to any specific amount of participation on the part of the authors, whose contribution to the AO remains voluntary (and unpaid). We suggest you try asking the authors some challenging questions, lest their interest stray! The AO forum and the archives of previous discussions will be accessible from the publisher's website as long as the book is in print. About the title By combining introductions, overviews, and how-to examples, the In Action books are designed to help you learn and remember. According to research in cognitive science, the things people remember are things they discover during self-motivated exploration. Although no one at Manning is a cognitive scientist, we're convinced that for learning to become permanent, it must pass through stages of exploration, play, and, interestingly, retelling of what's being learned. People understand and remember new things—that is, they master them—only after actively exploring them. Humans learn in action. An essential part of an In Action guide is that it's example-driven. It encourages the reader to try things out, play with new code, and explore new ideas. There is another, more mundane, reason for the title of this book: our readers are busy. They use books to do a job or solve a problem. They need books that allow them to jump in and jump out easily and learn just what they want just when they want it. They need books that aid them in action. The books in this series are designed for such readers. www.it-ebooks.info about the authors DEBU PANDA is a seasoned product manager, technologist, and community leader. He has authored more than 50 articles on Enterprise Java, Cloud, and SOA technologies and two books on Enterprise middleware. Follow Debu on Twitter @debupanda. REZA RAHMAN is a former long-time independent consultant and is now officially a Java EE/GlassFish evangelist at Oracle. Reza is a frequent speaker at Java user groups and conferences worldwide. He is an avid contributor to industry journals like JavaLobby/DZone and TheServerSide. Reza has been a member of the Java EE, EJB, and JMS expert groups. He implemented the EJB container for the Resin open source Java EE application server. RYAN CUPRAK is an e-formulation analyst at Dassault Systèmes (DS), author of the NetBeans Certification Guide from McGraw-Hill, and president of the Connecticut Java Users Group since 2003. He's also a JavaOne 2011 Rockstar Presenter. At DS he's focused on developing data integrations to convert clients' data, as well as user interface development. Prior to joining DS, he worked for a startup distributed-computing company, TurboWorx, and Eastman Kodak's Molecular Imaging Systems group, now part of Carestream Health. At TurboWorx he was a Java developer and a technical sales engineer supporting both presales and professional services. Cuprak earned a BS in computer science and biology from Loyola University Chicago. He is a Sun-certified NetBeans IDE specialist. xxiv www.it-ebooks.info ABOUT THE AUTHORS xxv MICHAEL REMIJAN is an operations manager and technical lead at BJC Hospital. Michael started working with Java EE in the late 1990s. He has developed Enterprise systems for B2C and B2B commerce, manufacturing, astronomy, agriculture, telecommunications, national defense, and healthcare. He earned a BS in computer science and mathematics from the University of Illinois in Urbana-Champaign and an MBA in technology management from the University of Phoenix. He has numerous Sun Microsystem certifications and has published articles with Java Developer's Journal and JavaLobby/DZone. His technology blog is mjremijan.blogspot.com. www.it-ebooks.info about the cover illustration The figure on the cover of EJB 3 in Action, Second Edition is captioned "Russian girl with fur," taken from a French travel book, Encyclopedie des Voyages by J. G. St. Saveur, published in 1796. Travel for pleasure was a relatively new phenomenon at the time and travel guides such as this one were popular, introducing both the tourist as well as the armchair traveler to the inhabitants of other regions of France and abroad. The diversity of the drawings in the Encyclopedie des Voyages speaks vividly of the uniqueness and individuality of the world's towns and provinces just 200 years ago. This was a time when the dress codes of two regions separated by a few dozen miles identified people uniquely as belonging to one or the other. The travel guide brings to life a sense of isolation and distance of that period and of every other historic period except our own hyperkinetic present. Dress codes have changed since then and the diversity by region, so rich at the time, has faded away. It is now often hard to tell the inhabitant of one continent from another. Perhaps, trying to view it optimistically, we've traded a cultural and visual diversity for a more varied personal life. Or a more varied and interesting intellectual and technical life. We at Manning celebrate the inventiveness, initiative, and fun of the computer business with book covers based on the rich diversity of regional life two centuries ago brought back to life by the pictures from this travel guide. xxvi www.it-ebooks.info Part 1 Overview of the EJB landscape T his book is about Enterprise Java Beans (EJB) 3, and covers up to the EJB 3.2 specification. The goal of EJB 3.2 is to continue to evolve the EJB specification to be a complete solution for all Enterprise business needs and to improve the EJB architecture by reducing its complexity from the developer's point of view. Part 1 presents EJB 3 as a powerful, highly usable platform worthy of its place as the business component development standard for mission-critical Enterprise development. We'll introduce the Java Persistence API (JPA 2.1), a Java EE technology that aims to standardize Java ORM and works hand-in-hand with EJB 3. We'll also take a quick look at Contexts and Dependency Injection for Java (CDI 1.1), the next-generation generic type-safe dependency injection technology for Java EE. In chapter 1 we introduce the pieces that make up EJB 3, touching on the unique strengths EJB has as a development platform and the new features that promote productivity and ease of use. We even throw in a "Hello World" example. In chapter 2 we provide more realistic code samples and introduce the ActionBazaar application, an imaginary Enterprise system developed throughout the book. We'll try to give you a feel for how EJB 3 looks as quickly and easily as possible. Be ready for a lot of code! www.it-ebooks.info www.it-ebooks.info What's what in EJB 3 This chapter covers ■ The EJB container and its role in Enterprise applications ■ The different types of Enterprise Java Beans (EJBs) ■ Closely related technologies such as the Java Persistence API (JPA) ■ The different EJB runtime environments ■ Innovations started with EJB 3 ■ New changes with EJB 3.2 One day, when God was looking over his creatures, he noticed a boy named Sadhu whose humor and cleverness pleased him. God felt generous that day and granted Sadhu three wishes. Sadhu asked for three reincarnations—one as a ladybug, one as an elephant, and the last as a cow. Surprised by these wishes, God asked Sadhu to explain himself. The boy replied, "I want to be a ladybug so that everyone in the world will admire me for my beauty and forgive the fact that I do no work. Being an elephant will be fun because I can gobble down enormous amounts of food without being ridiculed. I'll like being a cow the best because I'll be loved by all and 3 www.it-ebooks.info 4 CHAPTER 1 What's what in EJB 3 useful to mankind." God was charmed by these answers and allowed Sadhu to live through the three incarnations. He then made Sadhu a morning star for his service to humankind as a cow. EJB too has lived through three major incarnations. When it was first released, the industry was dazzled by its innovations. But like the ladybug, EJB 1 had limited functionality. The second EJB incarnation was almost as heavy as the largest of our beloved pachyderms. The brave souls who couldn't do without its elephant power had to tame the awesome complexity of EJB 2. And finally, in its third incarnation, EJB has become much more useful to the huddled masses, just like the gentle bovine that's sacred for Hindus and respected as a mother whose milk feeds us well. A lot of hard work from a lot of good people made EJB 3 simple and lightweight without sacrificing Enterprise-ready power. EJB components can now be Plain Old Java Objects (POJOs) and look a lot like code in a "Hello World" program. In the following chapters we'll describe a star among frameworks with increasing industry adoption. We've strived to keep this book practical without skimping on content. The book is designed to help you learn EJB 3 quickly and easily without neglecting the basics. We'll also dive into deep waters, sharing all the amazing sights we've discovered and warning about any lurking dangers. In the Java world EJB is an important and uniquely influential technology radically transformed in version 3. We'll spend little time with EJB 2. You probably either already know earlier versions of EJB or are completely new to it. Spending too much time on previous versions is a waste of time. EJB 3 and EJB 2 have very little in common, and EJB 3.2 now makes support for EJB 2 optional. But if you're curious about EJB 2, we encourage you to pick up one of the many good books on the previous versions of EJB. In this chapter we'll tell you what's what in EJB 3, explain why you should consider using it, and outline the significant improvements the newest version offers, such as annotations, convention-over-configuration, and dependency injection. We'll build on the momentum of this chapter by jumping into code in chapter 2. Let's start with a broad overview of EJB. 1.1 EJB overview The first thing that should cross your mind while evaluating any technology is what it really gives you. What's so special about EJB? Beyond a presentation-layer technology like JavaServer Pages (JSP), JavaServer Faces (JSF), or Struts, couldn't you create your web application using the Java language and some APIs like Java Database Connectivity (JDBC) for database access? You could—if deadlines and limited resources weren't realities. Before anyone dreamed up EJB, this is exactly what people did. The resulting long hours proved that you'd spend a lot of time solving very common system-level problems instead of focusing on the real business solution. These experiences emphasized that there are common solutions for common development problems. This is exactly what EJB brings to the table. EJB is a collection of "canned" answers to common server application development problems, as well as a roadmap to common server component www.it-ebooks.info EJB overview 5 patterns. These canned solutions or services are provided by the EJB container. To access these services, you build specialized components using declarative and programmatic EJB APIs and deploy them into the container. 1.1.1 EJB as a component model In this book, EJBs refer to server-side components that you can use to build the business component layer of your application. Some developers associate the term component with developing complex and heavyweight CORBA or Microsoft COM+ code. In the brave new world of EJB 3, a component is what it ought to be—nothing more than a POJO with some special powers. More importantly, these powers stay invisible until they're needed and don't distract from the real purpose of the component. You'll see this firsthand throughout this book, especially starting in chapter 2. To use EJB services, your component must be declared to be a recognized EJB component type. EJB recognizes two specific types of components: session beans and message-driven beans. Session beans are further subdivided into stateless session beans, stateful session beans, and singletons. Each component type has a specialized purpose, scope, state, lifecycle, and usage pattern in the business logic tier. We'll discuss these component types throughout the rest of the book, particularly in part 2. For data CRUD (create, read, update, delete) operations in the persistence tier, we'll talk about JPA entities and their relationship with EJBs in detail in part 3. As of EJB 3.1, all EJBs are managed beans. Managed beans are basically any generic Java object in a Java EE environment. Contexts and Dependency Injection (CDI) allows you to use dependency injection with all managed beans, including EJBs. We'll explore CDI and managed beans further in part 3. 1.1.2 EJB component services As we mentioned, the canned services are the most valuable part of EJB. Some of the services are automatically attached to recognize components because they make a lot of sense for business logic-tier components. These services include dependency injection, transactions, thread safety, and pooling. To use most services, you must declare you want them using annotations/XML or by accessing programmatic EJB APIs. Examples of such services include security, scheduling, asynchronous processing, remoting, and web services. Most of this book will be spent explaining how you can exploit EJB services. We can't explain the details of each service in this chapter, but we'll briefly list the major ones in table 1.1 and explain what they mean to you. Table 1.1 EJB services Service What it means for you Registry, dependency injection, and lookup Helps locate and glue together components, ideally through simple configuration. Lets you change component wiring for testing. Lifecycle management Lets you take appropriate actions when the lifecycle of a component changes, such as when it's created and when it's destroyed. www.it-ebooks.info 6 CHAPTER 1 What's what in EJB 3 Table 1.1 EJB services (continued) Service What it means for you Thread safety EJB makes all components thread-safe and highly performant in ways that are completely invisible to you. This means that you can write your multithreaded server components as if you were developing a single-threaded desktop application. It doesn't matter how complex the component is; EJB will make sure it's thread-safe. Transactions EJB automatically makes all of your components transactional, which means you don't have to write any transaction code while using databases or messaging servers via JDBC, JPA, or Java Message Service (JMS). Pooling EJB creates a pool of component instances that are shared by clients. At any point in time, each pooled instance can only be used by a single client. As soon as an instance is done servicing a client, it's returned to the pool for reuse instead of being frivolously discarded for the garbage collector to reclaim. You can also specify the size of the pool so that when the pool is full, any additional requests are automatically queued. This means that your system will never become unresponsive trying to handle a sudden burst of requests. Similar to instance pooling, EJB also automatically pools threads across the container for better performance. State management The EJB container manages the state transparently for stateful components instead of having you write verbose and error-prone code for state management. This means that you can maintain the state in instance variables as if you were developing a desktop application. EJB takes care of all the details of session/state maintenance behind the scenes. Memory management EJB steps in to optimize memory by saving less frequently used stateful components into the hard disk to free up memory. This is called passivation. When memory becomes available again and a passivated component is needed, EJB puts the component back into memory. This is called activation. Messaging EJB 3 allows you to write message processing components without having to deal with a lot of the mechanical details of the JMS API. Security EJB allows you to easily secure your components through simple configuration. Scheduling EJB lets you schedule any EJB method to be invoked automatically based on simple repeating timers or cron expressions. Asynchronous processing You can configure any EJB method to be invoked asynchronously if needed. Interceptors EJB 3 introduces AOP (aspect-oriented programming) in a lightweight, intuitive way using interceptors. This allows you to easily separate out crosscutting concerns such as logging and auditing, and to do so in a configurable way. Web services EJB 3 can transparently turn business components into Simple Object Access Protocol (SOAP) or Representational State Transfer (REST) web services with minimal or no code changes. Remoting In EJB 3, you can make components remotely accessible without writing any code. In addition, EJB 3 enables client code to access remote components as if they were local components using dependency injection (DI). Testing You can easily unit- and integration-test any EJB component using embedded containers with frameworks like JUnit. www.it-ebooks.info EJB overview 1.1.3 7 Layered architectures and EJB Enterprise applications are designed to solve a unique type of problem and therefore share many common requirements. Most Enterprise applications have some kind of user interface, implement business processes, model a problem domain, and save data into a database. Because of these shared requirements, you can follow a common architecture or design principle for building Enterprise applications known as patterns. For server-side development, the dominant pattern is layered architectures. In a layered architecture, components are grouped into tiers. Each tier in the application has a well-defined purpose, like a section of a factory assembly line. Each section of the assembly line performs its designated task and passes the remaining work down the line. In layered architectures, each layer delegates work to a layer underneath it. EJB recognizes this fact and thus isn't a jack-of-all-trades, master-of-none component model. Rather, EJB is a specialist component model that fits a specific purpose in layered architectures. Layered architectures come in two predominant flavors: traditional four-tier architectures and domain-driven design (DDD). Let's take a look at each of these architectures and where EJB is designed to fit in them. TRADITIONAL FOUR-TIER LAYERED ARCHITECTURE Figure 1.1 shows the traditional four-tier server architecture. This architecture is pretty intuitive and enjoys a good amount of popularity. In this architecture, the presentation layer is responsible for rendering the graphical user interface (GUI) and handling user input. The presentation layer passes down each request for application functionality to the business logic layer. The business logic layer is the heart of the application and contains workflow and processing logic. In other words, business logic– layer components model distinct actions or processes that the application can perform, such as billing, search, ordering, and user account maintenance. The business logic layer retrieves data from and saves data into the database by utilizing the persistence Presentation layer Business logic layer Persistence layer Database layer www.it-ebooks.info Figure 1.1 Most traditional Enterprise applications have at least four layers: the presentation layer is the actual user interface and can either be a browser or a desktop application; the business logic layer defines the business rules; the persistence layer deals with interactions with the database; and the database layer consists of a relational database such as Oracle database that stores the persistent objects. 8 CHAPTER 1 What's what in EJB 3 Security Integration Asynch Pooling Remoteability Business logic layer Thread safety Web services Scheduling Transactions Messaging Persistence layer Figure 1.2 The component services offered by EJB 3 at the supported application layer. Note that each service is independent of the others, so you are (for the most part) free to pick the features important for your application. tier. The persistence layer provides a high-level object-oriented (OO) abstraction over the database layer. The database layer typically consists of a relational database management system (RDBMS) like Oracle database, DB2 database, or SQL Server database. EJB isn't a presentation layer or persistence-layer technology. It's all about robust support for implementing business logic-layer components for Enterprise applications. Figure 1.2 shows how EJB supports these layers via its services. In a typical Java EE-based system, JSF and CDI will be used at the presentation tier, EJB will be used in the business layer, and JPA and CDI will be used in the persistence tier. The traditional four-tier layered architecture isn't perfect. One of the most common criticisms is that it undermines the OO ideal of modeling the business domain as objects that encapsulate both data and behavior. Because the traditional architecture focuses on modeling business processes instead of the domain, the business logic tier tends to look more like a database-driven procedural application than an OO one. Because persistence-tier components are simple data holders, they look a lot like database record definitions rather than first-class citizens of the OO world. As you'll see in the next section, DDD proposes an alternative architecture that attempts to solve these perceived problems. DOMAIN-DRIVEN DESIGN Figure 1.3 shows domain-driven architecture. The term domain-driven design may be relatively new but the concept is not (see Domain-Driven Design: Tackling Complexity in the Heart of Software, by Eric Evans [Addison-Wesley Professional, 2003]). DDD emphasizes that domain objects should contain business logic and shouldn't just be dumb replicas of database records. Domain objects can be implemented as entities in JPA. With DDD, a Catalog object in a trading application might, in addition to having all the data of an entry in the catalog table in the database, know not to return catalog entries that aren't in stock. Being POJOs, JPA entities support OO features, such as inheritance and polymorphism. It's easy to implement a persistence object model with the JPA and to add business logic to your entities. Now, DDD still utilizes a service layer or application layer (see Patterns of Enterprise Application Architecture, by Martin Fowler www.it-ebooks.info 9 EJB overview Figure 1.3 Domain-driven design typically has four or more layers. The presentation layer is responsible for the user interface and for interaction with the application/service layer. The application/service layer is typically very light and only allows communication between the presentation layer and the domain. The domain layer is the complex expression of your application data model consisting of entities, value objects, aggregates, factories, and repositories. The infrastructure layer gets to the database and other similar technology. [Addison-Wesley Professional, 2002]). The application layer is similar to the business logic layer of the traditional four-tier architecture but much thinner. EJB works well as the service-layer component model. Whether you use the traditional four-tier architecture or a layered architecture with DDD, you can use entities to model domain objects, including modeling state and behavior. We'll discuss domain modeling with JPA entities in chapter 7. Despite its impressive services and vision, EJB 3 isn't the only act in town. You can combine various technologies to more or less match EJB services and infrastructure. For example, you could use Spring with other open-source technologies such as Hibernate and AspectJ to build your application, so why choose EJB 3? Glad that you asked.... 1.1.4 Why choose EJB 3? At the beginning of this chapter, we hinted at EJB's status as a pioneering technology. EJB is a groundbreaking technology that raised the standards of server-side development. Just like Java itself, EJB changed things in ways that are here to stay and inspired many innovations. Up until a few years ago, the only serious competition to EJB came from the Microsoft .NET framework. In this section, we'll point out a few of the compelling EJB 3 features that we feel certain will have this latest version at the top of your short list. EASE OF USE Thanks to the unwavering focus on ease of use, EJB 3 is probably the simplest serverside development platform around. The features that shine the brightest are POJO programming, annotations in favor of verbose XML, heavy use of sensible defaults, and avoidance of complex paradigms. Although the number of EJB services is significant, you'll find them very intuitive. For the most part, EJB 3 has a practical outlook on things and doesn't demand that you understand the theoretical intricacies. In fact, www.it-ebooks.info 10 CHAPTER 1 What's what in EJB 3 most EJB services are designed to give you a break from this mode of thinking so you can focus on getting the job done and go home at the end of the day knowing you accomplished something. COMPLETE, INTEGRATED SOLUTION STACK EJB 3 offers a complete stack of server-side solutions, including transactions, security, messaging, scheduling, remoting, web services, asynchronous processing, testing, dependency injection, and interceptors. This means that you won't have to spend a lot of time looking for third-party tools to integrate into your application. These services are also just there for you—you don't have to do anything to explicitly enable them. This leads to near-zero configuration systems. In addition, EJB 3 provides seamless integration with other Java EE technologies, such as CDI, JPA, JDBC, JavaMail, Java Transaction API (JTA), JMS, Java Authentication and Authorization Service (JAAS), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), and so on. EJB is also guaranteed to seamlessly integrate with presentation-tier technologies like JSP, Servlets, and JSF. When needed, you can integrate third-party tools with EJB using CDI. OPEN JAVA EE STANDARD EJB is a critical part of the Java EE standard. This is an extremely important concept to grasp if you're to adopt EJB. EJB 3 has an open, public API specification and compati- bility test kit that organizations are encouraged to use to create a container implementation. The EJB 3 standard is developed by the Java Community Process (JCP), consisting of a nonexclusive group of individuals driving the Java standard. The open standard leads to broader vendor support for EJB 3, which means you don't have to depend on a proprietary solution. BROAD VENDOR SUPPORT EJB is supported by a large and diverse variety of independent organizations. This includes the technology world's largest, most respected, and most financially strong names, such as Oracle and IBM, as well as passionate and energetic open-source groups like JBoss and Apache. Wide vendor support translates to three important advantages for you. First, you're not at the mercy of the ups and downs of a particular company or group of people. Second, a lot of people have concrete long-term interests in keeping the technology as competitive as possible. You can essentially count on being able to take advantage of the best-of-breed technologies both in and outside the Java world in a competitive timeframe. Third, vendors have historically competed against one another by providing value-added nonstandard features. All of these factors help keep EJB on the track of continuous healthy evolution. CLUSTERING, LOAD BALANCING, AND FAILOVER Features historically added by most application server vendors are robust support for clustering, load balancing, and failover. EJB application servers have a proven track record of supporting some of the largest high-performance computing (HPC)– enabled server farm environments. More importantly, you can use such support with www.it-ebooks.info Understanding EJB types 11 no changes to code, no third-party tool integration, and relatively simple configuration (beyond the inherent work in setting up a hardware cluster). This means that you can rely on hardware clustering to scale up your application with EJB 3 if you need to. PERFORMANCE AND SCALABILITY Enterprise applications have a lot in common with a house. Both are meant to last, often much longer than anyone expects. Being able to support high-performance, fault-tolerant, scalable applications is an upfront concern for the EJB platform instead of being an afterthought. Not only will you be writing good server-side applications faster, you can also expect your platform to grow as needed. You can support a larger number of users without having to rewrite your code; these concerns are taken care of by EJB container vendors via features like thread safety, distributed transactions, pooling, passivation, asynchronous processing, messaging, and remoting. You can count on doing minimal optimization or moving your application to a distributed, clustered server farm by doing nothing more than a bit of configuration. We expect that by now you're getting jazzed about EJB and you're eager to learn more. So let's jump right in and see how you can use EJB to build the business logic tier of your applications, starting with the beans. 1.2 Understanding EJB types In EJB-speak, a component is a bean. If your manager doesn't find the Java "coffee bean" play on words cute either, blame Sun's marketing department. Hey, at least you get to hear people in suits use the words "Enterprise" and "bean" in close sequence as if it were perfectly normal. As we mentioned, EJB classifies beans into two types based on what they're used for: ■ ■ Session beans Message-driven beans Each bean type serves a purpose and can use a specific subset of EJB services. The real purpose of bean types is to safeguard against overloading them with services that cross wires. This is kind of like making sure the accountant in the horn-rimmed glasses doesn't get too curious about what happens when you touch both ends of a car battery terminal at the same time. Bean classification also helps you understand and organize an application in a sensible way; for example, bean types help you develop applications based on a layered architecture. Let's start digging a little deeper into the various EJB component types, starting with session beans. 1.2.1 Session beans A session bean is invoked by a client to perform a specific business operation, such as checking the credit history of a customer. The name session implies that a bean instance is available for the duration of a unit of work and doesn't survive a server crash or shutdown. A session bean can model any application logic functionality. There are three types of session beans: stateful, stateless, and singleton. www.it-ebooks.info 12 CHAPTER 1 What's what in EJB 3 A stateful session bean automatically saves the bean state between invocations from a single, unique client without your having to write any additional code. The typical example of a state-aware process is the shopping cart for a web merchant like Amazon. Stateful session beans are either timed out or end their lifecycle when the client requests it. In contrast, stateless session beans don't maintain any state and model application services that can be completed in a single client invocation. You could build stateless session beans for implementing business processes such as charging a credit card or checking a customer's credit history. Singleton session beans maintain the state, are shared by all clients, and live for the duration of the application. You could use a singleton bean for a discount processing component since the business rules for applying discounts are usually fixed and shared across all clients. Note that singleton beans are a new feature added in EJB 3.1. A session bean can be invoked either locally or remotely using Java RMI. A stateless or singleton session bean can also be exposed as a SOAP or REST web service. 1.2.2 Message-driven beans Like session beans, message-driven beans (MDBs) process business logic. But MDBs are different in one important way: clients never invoke MDB methods directly. Instead, MDBs are triggered by messages sent to a messaging server, which enables sending asynchronous messages between system components. Some typical examples of messaging servers are HornetQ, ActiveMQ, IBM WebSphere MQ, SonicMQ, Oracle Advanced Queueing, and TIBCO. MDBs are typically used for robust system integration and asynchronous processing. An example of messaging is sending an inventory-restocking request from an automated retail system to a supply-chain management system. Don't worry too much about messaging right now; we'll get to the details later in this book. 1.3 Related specifications EJB has two closely related specifications that we'll cover in this book. The first is JPA, which is the persistence standard for Java EE and CDI, and provides dependency injection and context management services to all Java EE components including EJB. 1.3.1 Entities and the Java Persistence API EJB 3.1 saw JPA 2 moved from an EJB 3 API to a completely separate Java EE specification. But JPA has some specific runtime integration points with EJB because the specifications are so closely related. We'll say just a few things about JPA here because we have chapters dedicated to it. Persistence is the ability to have data contained in Java objects automatically stored into a relational database like Oracle database, SQL server database, and DB2 database. Persistent objects are managed by JPA. It automatically persists Java objects using a technique called object-relational mapping (ORM). ORM is the process of mapping data held in Java objects to database tables using configuration or declaratively using annotations. It relieves you of the task of writing low-level, boring, and complex JDBC code to persist objects into a database. www.it-ebooks.info Related specifications 13 An ORM framework performs transparent persistence by making use of ORM metadata that defines how objects are mapped to database tables. ORM isn't a new concept and has been around for a while. Oracle TopLink is probably the oldest ORM framework in the market; open-source framework JBoss Hibernate popularized ORM concepts within the mainstream developer community. Because JPA standardizes ORM frameworks for the Java platform, you can plug in an ORM product like JBoss Hibernate, Oracle TopLink, or Apache OpenJPA as the underlying JPA "persistence provider" for your application. JPA isn't just a solution for server-side applications. Persistence is a problem that even a standalone Swing-based desktop application has to solve. This drove the decision to make JPA 2 a cleanly separated API in its own right that can be run outside an EJB 3 container. Much like JDBC, JPA is intended to be a general-purpose persistence solution for any Java application. ENTITIES Entities are the Java objects that are persisted into the database. While session beans are the "verbs" of a system, entities are the "nouns." Common examples include an Employee entity, a User entity, and an Item entity. Entities are the OO representations of the application data stored in the database. Entities survive container crashes and shutdown. The ORM metadata specifies how the object is mapped to the database. You'll see an example of this in the next chapter. JPA entities support a full range of relational and OO capabilities, including relationships between entities, inheritance, and polymorphism. ENTITYMANAGER Entities tell a JPA provider how they map to the database, but they don't persist themselves. The EntityManager interface reads the ORM metadata for an entity and performs persistence operations. The EntityManager knows how to add entities to the database, update stored entities, and delete and retrieve entities from the database. JAVA PERSISTENCE QUERY LANGUAGE JPA provides a specialized SQL-like query language called Java Persistence Query Language (JPQL) to search for entities saved into the database. With a robust and flexible API such as JPQL, you won't lose anything by choosing automated persistence instead of handwritten JDBC. In addition, JPA supports native, database-specific SQL, in the rare cases where it's worth using. 1.3.2 Contexts and dependency injection for Java EE Java EE 5 had a basic form of dependency injection that EJB could use. It was called resource injection and allowed you to inject container resources, such as data sources, queues, JPA resources, and EJBs, using annotations like @EJB, @Resource, and @PersistenceContext. These resources could be injected into Servlets, JSF backing beans, and EJB. The problem was that this was very limiting. You weren't able to inject EJB into Struts or JUnit, and you couldn't inject non-EJB DAOs (data access objects) or helper classes into EJB. www.it-ebooks.info 14 CHAPTER 1 What's what in EJB 3 CDI is a powerful solution to the problem. It provides EJB (as well as all other APIs and components in the Java EE environment) best-of-breed, next-generation, generic dependency injection and context management services. CDI features include injection, automatic context management, scoping, qualifiers, component naming, producers, disposers, registry/lookup, stereotypes, interceptors, decorators, and events. Unlike many older dependency injection solutions, CDI is completely type-safe, compact, futuristic, and annotation-driven. We'll cover CDI in detail in chapter 12. 1.4 EJB runtimes When you build a simple Java class, you need a Java Virtual Machine (JVM) to execute it. In a similar way (as you learned in section 1.3), to execute session beans and MDBs you need an EJB container. In this section we give you a bird's-eye view of the different runtimes that an EJB container may contain inside. Think of the container as an extension of the basic idea of a JVM. Just as the JVM transparently manages memory on your behalf, the container transparently provides EJB component services such as transactions, security management, remoting, and web services support. You might even think of the container as a JVM on steroids, of which the purpose is to execute EJB. In EJB 3, the container provides services applicable only to session beans and MDBs. The task of putting an EJB 3 component inside a container is called deployment. Once an EJB is successfully deployed in a container, it can be used in your applications. In the Java world, containers aren't limited to the realm of EJB 3. You're probably familiar with a web container, which allows you to run web-based applications using Java technologies such as Servlets, JSP, and JSF. A Java EE container is an application server solution that supports EJB 3, a web container, and other Java EE APIs and services. Oracle WebLogic server, GlassFish server, IBM WebSphere application server, JBoss application server, and Caucho Resin are examples of Java EE containers. 1.4.1 Application servers Application servers are where EJBs have been traditionally deployed. Application servers are Java EE containers that include support for all Java EE APIs, as well as facilities for administration, deployment, monitoring, clustering, load balancing, security, and so on. In addition to supporting Java EE-related technologies, some application servers can also function as production-quality HTTP servers. Others support modularity via technologies like OSGi. As of Java EE 6, application servers can also come in a scaled-down, lightweight Web Profile form. The Web Profile is a smaller subset of Java EE APIs specifically geared toward web applications. Web Profile APIs include JSF 2.2, CDI 1.1, EJB 3.2 Lite (discussed in section 1.4.2), JPA 2.1, JTA 1.2, and bean validation. At the time of writing, GlassFish and Resin provided Java EE 7 Web Profile offerings. Note that Java EE 7 Web Profile implementations are free to add APIs as they wish. For example, Resin adds JMS, as well as most of the EJB API including messaging, remoting, and scheduling (but not EJB 2 backward compatibility). Figure 1.4 shows how the Web Profile compares with the complete Java EE platform. www.it-ebooks.info 15 EJB runtimes Figure 1.4 Java EE Web Profile versus full Java EE platform The Web Profile defines a complete stack on which to build a modern web application. Web applications are now rarely written from the ground up using raw Servlets, but instead sit on top of JSF and make use of the various EE technologies. 1.4.2 EJB Lite Similar to the idea of the Java EE 7 Web Profile, EJB 3.2 also comes in a scaled-down, lighter-weight version called EJB 3.2 Lite. EJB Lite goes hand-in-hand with the Web Profile and is intended for web applications. Just as with the Web Profile, any vendor implementing the EJB 3.2 Lite API is free to include EJB features as they wish. From a practical standpoint, the most important thing that EJB 3.2 Lite does is remove support for EJB 2 backward compatibility. This means that an EJB container can be much more lightweight because it doesn't have to implement the old APIs in addition to the lightweight EJB 3 model. Because EJB 3.2 Lite also doesn't include support for MDBs and remoting, it can mean a lighter-weight server if you don't need these features. For reference, table 1.2 compares the major EJB and EJB Lite features. Table 1.2 EJB and EJB Lite feature comparison Feature EJB Lite Stateless beans Stateful beans Singleton beans Message-driven beans No interfaces Local interfaces Remote interfaces Web service interfaces www.it-ebooks.info EJB 16 CHAPTER 1 What's what in EJB 3 Table 1.2 EJB and EJB Lite feature comparison (continued) Feature EJB Lite EJB Asynchronous invocation Interceptors Declarative security Declarative transactions Programmatic transactions Timer service EJB 2.x support CORBA interoperability 1.4.3 Embeddable containers Traditional application servers run as a separate process that you deploy your applications into. Embedded EJB containers, on the other hand, can be started through a programmatic Java API inside your own application. This is very important for unit testing with JUnit as well as using EJB 3 features in command-line or Swing applications. When an embedded container starts, it scans the class path of your application and automatically deploys any EJBs it can find. Figure 1.5 shows the architecture of an embedded EJB 3 container. Embeddable containers have been around for a while. OpenEJB, EasyBeans, and Embedded JBoss are examples. Embeddable containers are only required to support EJB Lite, but most implementations are likely to support all features. For example, the embedded versions of GlassFish, JBoss, and Resin support all the features available on the application server. We'll discuss embedded containers in detail in chapter 15 on testing EJB 3. 1.4.4 Using EJB 3 in Tomcat Apache Tomcat, the lightweight, popular Servlet container, doesn't support EJB 3, because unlike application servers, Servlet containers aren't required to support EJB. But you can easily use EJB 3 on Tomcat through embedded containers. The Apache EJB embedded container Transaction manager Security system Java SE Messaging engine Figure 1.5 EJB 3.1 embedded containers run directly inside Java SE and provide all EJB services such as transactions, security, and messaging. www.it-ebooks.info 17 Brave new innovations Figure 1.6 You can use OpenEJB and OpenWebBeans to enable both EJB and CDI on Tomcat. OpenEJB project has specific support for enabling EJB 3 on Tomcat. As shown in figure 1.6, you can also enable CDI on Tomcat using Apache OpenWebBeans. OpenWebBeans and OpenEJB are closely related projects and work seamlessly together. In this way, you can use a majority of Java EE 7 APIs on Tomcat if you wish. 1.5 Brave new innovations From this point onward, let's start getting a little down and dirty and seeing what the brave new world of EJB 3 looks like in code. We'll note the primary distinguishing features of EJB 3 along the way. 1.5.1 "Hello User" example "Hello World" examples have ruled the world since they first appeared in The C Programming Language by Brian Kernighan and Dennis Ritchie (Prentice Hall PTR, 1988). "Hello World" caught on and held ground for good reason. It's very well suited to introducing a technology as simply and plainly as possible. The code samples for this book will use Maven, and if you're using Eclipse, you'll find it useful to have the m2eclipse plug-in installed to integrate Eclipse with Maven. In 2004, one of the authors, Debu Panda, wrote an article for the TheServerSide.com in which he stated that when EJB 3 was released, it would be so simple you could write a "Hello World" in it using only a few lines of code. Any experienced EJB 2 developer knows that this couldn't be done easily in EJB 2. You had to write a home interface, a component interface, a bean class, and a deployment descriptor. Well, let's see if Debu was right in his prediction, as shown in the following listing. Listing 1.1 HelloUser session bean package ejb3inaction.example; import javax.ejb.Stateless; b Stateless annotation c HelloUserBean @Stateless POJO public class HelloUserBean implements HelloUser { public String sayHello(String name) { return String.format("Hello %s welcome to EJB 3.1!",name); } } This listing is a complete and working EJB! The bean class is a POJO B, without even an interface. EJB 3.1 introduced the no-interface view. Before this, EJB required an interface to indicate which methods should be visible. The no-interface view essentially says that all public methods in your bean will be available for invocation. It's easy to www.it-ebooks.info 18 CHAPTER 1 What's what in EJB 3 use, but you need to pick your public methods carefully. The exposeAllTheCompanysDirtySecrets() method should probably be private. The funny @Stateless symbol in listing 1.1 is a metadata annotation c that converts the POJO to a full-powered stateless EJB. In effect, they're "comment-like" configuration information that can be added to Java code. EJB 3 enables you to develop an EJB component using POJOs that know nothing about platform services. You can apply annotations to these POJOs to add platform services such as remoteability, web services support, and lifecycle callbacks as needed. To execute this EJB, you have to deploy it to the EJB container. If you want to execute this sample, download the actionbazaar-snapshot-2.zip from https://code.google.com/ p/action-bazaar/, extract "chapter1 project" to build, and install it using Maven and the embedded GlassFish server. We're going to analyze a lot of code in this book—some just as easy as this. You could trigger the hello as a web service by simply adding the @WebService annotation. You could inject a resource, like a helper bean that will translate hello into foreign languages, with @Inject. What do you want to do with EJB? If you keep reading, we'll probably tell you how to do it. 1.5.2 Annotations versus XML Prior to annotations (introduced in Java SE 5), XML was the only logical choice for application configuration because there were no other viable options around, except for tools like XDoclet, which was popular in many relatively progressive EJB 2 shops. The problems with XML are myriad. XML is verbose, not that readable, and extremely error-prone. XML also takes no advantage of Java's unique strength in strong type safety. Lastly, XML configuration files tend to be monolithic and they separate the information about the configuration from the Java code that uses them, making maintenance more difficult. Collectively, these problems are named XML Hell and annotations are specifically designed to be the cure. EJB 3 was the first mainstream Java technology to pave the way for annotation adoption. Since then, many other tools like JPA, JSF, Servlets, JAX-WS, JAX-RS, JUnit, Seam, Guice, and Spring have followed suit. As you can see in the code example in listing 1.1, annotations are essentially property settings that mark a piece of code, such as a class or method, as having particular attributes. When the EJB container sees these attributes, it adds the container services that correspond to it. This is called declarative-style programming, where the developer specifies what should be done and the system adds the code to do it behind the scenes. In EJB 3, annotations dramatically simplify development and testing of applications. Developers can declaratively add services to EJB components when they need to. As figure 1.7 depicts, an annotation basically transforms a simple POJO into an EJB, just as the @Stateless annotation does in the example. www.it-ebooks.info Brave new innovations 19 Figure 1.7 EJBs are regular Java objects that may be configured using metadata annotations. While XML has its problems, it can be beneficial in some ways. It can be easier to see how the system components are organized by looking at a centralized XML configuration file. You can also configure the same component differently per deployment or configure components whose source code you can't change. Configuration that has little to do with Java code is also poorly expressed in annotations. Examples of this include port/URL configuration, file locations, and so on. The good news is that you can use XML with EJB 3. You can even use XML to override or augment annotation-based configuration. Unless you have a very strong preference for XML, it's generally advisable to start with annotations and use XML overrides where they're really needed. 1.5.3 Intelligent defaults versus explicit configuration EJB takes a different approach to default behavior than most frameworks such as Spring. With Spring, for example, if you don't ask, you don't get. You have to ask for any behavior you want to have in your Spring components. In addition to making the task of configuration easier via annotations, EJB 3 reduces the total amount of configuration altogether by using sensible defaults wherever possible. For example, the "Hello World" component is automatically thread-safe, pooled, and transactional without you having to do anything at all. Similarly, if you want scheduling, asynchronous processing, remoting, or web services, all you need to do is add a few annotations to the component. There's no service that you'll need to understand, explicitly enable, or configure—everything is enabled by default. The same is true of JPA and CDI as well. Intelligent defaulting is especially important when you're dealing with automated persistence using JPA. 1.5.4 Dependency injection versus JNDI lookup EJB 3 was reengineered from the ground up for dependency injection. This means that you can inject EJBs into other Java EE components and inject Java EE components into EJBs. This is especially true when using CDI with EJB 3. For example, if you want to access the HelloUser EJB in listing 1.1 from another EJB, Servlet, or JSF backing bean, you could use code like this: @EJB private HelloUserBean helloUser; b EJB injection void hello(){ helloUser.sayHello("Curious George"); } Isn't that great? The @EJB annotation B transparently "injects" the HelloUserBean EJB into the annotated variable. The @EJB annotation reads the type and name of the www.it-ebooks.info 20 CHAPTER 1 What's what in EJB 3 EJB and looks it up from JNDI under the hood. All EJB components are automatically registered with JNDI while being deployed. Note that you can still use JNDI lookups where they're unavoidable. For example, to dynamically look up your bean, you could use code like this: Context context = new InitialContext(); HelloUserBean helloUser = (HelloUserBean) context.lookup("java:module/HelloUserBean"); helloUser.sayHello("Curious George"); We'll talk in detail about EJB injection and lookup in chapter 5. 1.5.5 CDI versus EJB injection EJB-style injection predates CDI. Naturally, this means that CDI injection adds a number of improvements over EJB injection. Most importantly, CDI can be used to inject almost anything. EJB injection, on the other hand, can only be used with objects stored in JNDI, such as EJB, as well as some container-managed objects like the EJB context. CDI is far more type-safe than EJB. Generally speaking, CDI is a superset of EJB injection. For example, you can use CDI to inject the EJB as follows: @Inject private HelloUserBean helloUser; EJB injection via CDI void hello(){ helloUser.sayHello("Curious George"); } It might seem that CDI should be used for all Java EE injections, but it currently has a limitation. Although CDI can retrieve an EJB by type, it doesn't work with remote EJBs. EJB injection (@EJB) will recognize whether an EJB is local or remote and return the appropriate type. You should use CDI for injection when possible. 1.5.6 Testable POJO components Because all EJBs are simply POJOs, you can easily unit test them in JUnit for basic component functionality. You can even use CDI to inject EJBs directly into unit tests, wire mock objects, and so on. Thanks to embedded containers, you can even perform full integration testing of EJB components from JUnit. Projects like Arquillian focus specifically on integrating JUnit with embedded containers. The following listing shows how Arquillian allows you to inject EJBs into JUnit tests. Listing 1.2 EJB 3 unit testing with Arquillian package ejb3inaction.example; import import import import import import javax.ejb.EJB; org.jboss.arquillian.api.Deployment; org.jboss.arquillian.junit.Arquillian; org.jboss.shrinkwrap.api.Archive; org.jboss.shrinkwrap.api.ShrinkWrap; org.jboss.shrinkwrap.api.spec.JavaArchive; www.it-ebooks.info 21 Changes in EJB 3.2 import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class HelloUserBeanTest { @EJB private HelloUser helloUser; Running JUnit with Arquillian Injecting bean to be tested @Deployment public static Archive<?> createDeployment() { return ShrinkWrap.create(JavaArchive.class, "foo.jar") .addClasses(HelloUserBean.class); } @Test public void testSayHello() { String helloMessage = helloUser.sayHello("Curious George"); Assert.assertEquals( "Hello Curious George welcome to EJB 3.1!",helloMessage); } Using EJB in unit test } We've dedicated chapter 15 in its entirety to testing EJB components. 1.6 Changes in EJB 3.2 The goal of 3.2 is to continue to evolve the EJB specification to be a complete solution for all Enterprise business needs and to improve the EJB architecture by reducing its complexity from the developer's point of view. In this section we'll briefly talk about the particular changes in EJB 3.2. 1.6.1 1.6.2 Previous EJB 2 features now optional Support for EJB 2 has been made optional by EJB 3.2. This means a fully compliant Java EE 7 application server no longer needs to support EJB 2-style entities beans. EJB QL and JAX-RPC have also been made optional. Enhancements to message-driven beans In EJB 3.2, MDBs have been given a major overhaul. The update to JMS 2.0 brings a simplified API as well as integration with advances to Java in other areas such as dependency injection with CDI. It also makes using the javax.jms.MessageListener interface optional, giving you the ability to create an MDB with a no-methods listener interface, which makes public methods of the class message listener methods. Here's a quick look at the simplified API for MDB. Send a message: @Inject @JMSConnectionFactory("jms/QueueConnectionFactory") private JMSContext context; @Resource(lookup="jms/MessageQueue") private Queue queue; www.it-ebooks.info Injects destination Injects JMSContext 22 CHAPTER 1 What's what in EJB 3 public void sendMessage(String txtToSend) { context.createProducer().send(queue, txtToSend); } Uses simplified API to send message Annotated as an MDB for the container, listen on "jms/BidQueue" Receive a message: @MessageDriven(mappedName="jms/BidQueue") public class BidMdb implements MessageListener { @Resource private MessageDrivenContext mdc; public void onMessage(Message inMessage) { // handle message } Class implements MessageListener to receive JMS messages Injects a MessageDrivenContext if needed Method implements MessageListener and handles message } 1.6.3 Enhancements to stateful session beans In EJB 3.2, session beans haven't changed dramatically, at least not as dramatically as MDBs. A few enhancements have been made to stateful session beans concerning passivation and transaction support. Here's a quick look at these enhancements. DISABLE PASSIVATION Prior to EJB 3.2, stateful beans needed all objects in them to implement Serializable so that the EJB container could passivate a bean without error. If one object in your stateful bean wasn't serializable, passivation would fail and the EJB container would destroy the bean, losing the state. Although it's highly advisable to make sure your stateful beans are serializable so the EJB container can provide you with services like passivation and clustered failover, sometimes it's not possible. To prevent the container from attempting to passivate a stateful bean you don't want to passivate, use the passivationCapable element: @Stateful(passivationCapable=false) public class BiddingCart { } Prevents EJB container from passivating stateful bean TRANSACTION SUPPORT TO LIFECYCLE CALLBACKS Prior to EJB 3.2, stateful session beans had lifecycle callback methods, but it was undefined how transactions were supported during these method calls. So the new API adds transactional support to the lifecycle callback methods by introducing the ability to annotate the lifecycle callback methods with @TransactionalAttribute(REQUIRES_NEW). REQUIRES_NEW is the only valid value for stateful lifecycle callback methods: @Stateful public class BiddingCart { @PostConstruct @TransactionAttribute(REQUIRES_NEW) public void lookupDefaults() { } } Stateful session bean www.it-ebooks.info @PostConstruct lifecycle method lookupDefaults is run in its own transaction 23 Changes in EJB 3.2 1.6.4 Simplifying local interfaces for stateless beans Prior to 3.2, if interfaces weren't marked as @Local or @Remote, then the implementing bean was forced to define them. Here's what the pre-3.2 interface and bean looked like: public interface A {} public interface B {} Interfaces A and B don't specify @Local or @Remote @Stateless @Local({A.class, B.class}} public class BidServicesBean implements A, B {} b Prior to EJB 3.2, @Local must be used to define both A and B as local interfaces Now EJB 3.2 has more intelligent defaults. By default, all interfaces that don't specify @Local or @Remote automatically become local interfaces by the container. So you can skip line B and rewrite the code like this: @Stateless public class BidServicesBean implements A, B {} Container will now default A and B to local interfaces 1.6.5 Enhancements in TimerService API The TimerService API has been enhanced to expand the scope of where and how timers may be retrieved. Prior to EJB 3.2, the Timer and TimerHandler objects could only be accessed by the bean that owned the timer. This restriction has been lifted, and a new API method called getAllTimers() has been added that will return a list of all active timers in the EJB module. This allows any code to view all timers and have the ability to alter them. 1.6.6 Enhancements in EJBContainer API For EJB 3.2, a couple of changes have been made to the embeddable EJBContainer API. First, the API now implements AutoCloseable so it may be used with a try-withresources statement: try (EJBContainer c = EJBContainer.createEJBContainer();) { // work with container } Second, the embeddable EJBContainer object is required to support the EJB Lite group of the EJB API. EJB API groups will be discussed further in the next section. 1.6.7 EJB API groups Because EJB technology is the backbone of Enterprise Java development, EJBs need to be able to provide a large number of services to fulfill business needs. These services include but aren't limited to transactions, security, remote access, synchronous and asynchronous execution, and state tracking, and the list goes on. Not all Enterprise solutions require all the services EJBs are able to provide. To help streamline usage, EJB API groups were created for EJB 3.2. EJB API groups are well-defined subsets of the capabilities of EJBs created for specific purposes. The groups defined in the EJB 3.2 specification are these: www.it-ebooks.info 24 CHAPTER 1 What's what in EJB 3 ■ EJB Lite ■ Message-driven beans EJB 3.x Remote Persistent EJB timer services JAX-WS Web Service endpoints Embeddable EJB container (optional) EJB 2.x API Entity beans (optional) JAX-RPC Web Service endpoints (optional) ■ ■ ■ ■ ■ ■ ■ Except for the few groups that are optional, a full EJB container is required to implement all of the groups. The most important of these is the EJB Lite group. The EJB Lite group consists of the minimum number of EJB features that's still powerful enough to handle the majority of business transactions and security needs. This makes an EJB Lite implementation ideal to embed into a Servlet container like Tomcat to give the container some Enterprise features, or you can embed it into your Android tablet application to handle its data needs. Now that we've looked at some of the new features and changes made to EJB 3.2, let's see how EJB technology compares with other frameworks in the marketplace that are also attempting to provide solutions for Enterprise Java software development. 1.7 Summary You should now have a good idea of what EJB 3 is, what it brings to the table, and why you should consider using it to build server-side applications. We gave you an overview of the new features in EJB 3, including these important points: ■ ■ ■ EJB 3 components are POJOs that are configurable through simplified meta- data annotations. Accessing EJB from client applications and unit tests has become very simple using dependency injection. EJB provides a powerful, scalable, complete set of Enterprise services out-of-the-box. We also provided a taste of code to show how EJB 3 addresses development pain points. Armed with this essential background, you're probably eager to look at more code. We aim to satisfy this desire, at least in part, in the next chapter. Get ready for a whirlwind tour of the EJB 3 API that shows just how easy the code really is. www.it-ebooks.info A first taste of EJB This chapter covers ■ The ActionBazaar application ■ Stateless and stateful session beans in ActionBazaar ■ Integrating CDI and EJB 3 ■ Persisting objects with JPA 2 In the age of globalization, learning a new technology by balancing a book on your lap while hacking away at a business problem on the keyboard has become the norm. Let's face it—somewhere deep down you probably prefer this "baptism by fire" to trudging the same old roads over and over again. This chapter is for the brave pioneer in all of us, eager to peek over the horizon into the new world of EJB 3. The first chapter gave you a 20,000-foot view of the EJB 3 landscape from a hypersonic jet. We defined EJB, described the services it offers and the EJB 3 architectural blueprint, and described how EJB 3 is related to CDI and JPA 2. This chapter is a low-altitude flyover with a reconnaissance airplane. Here we'll take a quick look at the code for solving a realistic problem using EJB 3, JPA 2, and CDI. The example solution will use some of the EJB 3 component types, a layered architecture, 25 www.it-ebooks.info 26 CHAPTER 2 A first taste of EJB and some of the services we discussed in chapter 1. You'll see firsthand exactly how easy and useful EJB 3 is and how quickly you could pick it up. If you aren't a big fan of views from heights, don't worry. Think of this chapter as that first day at a new workplace, shaking hands with the strangers in the neighboring cubicles. In the chapters that follow, you'll get to know more about your new coworkers' likes, dislikes, and eccentricities, and you'll learn how to work around these foibles. All you're expected to do right now is put names to faces. Running the example code At this point, we encourage you to start exploring the code examples for this book. You can peek at the entire solution by downloading the zip file containing the code examples from www.manning.com/panda2. We highly recommend that you set up your favorite development environment with the code. That way, you can follow along with us and even tinker with the code on your own, including running it inside a container. The problem you'll solve in this chapter utilizes an essential element of this book— ActionBazaar. ActionBazaar is an imaginary enterprise system around which we'll weave most of the material in this book. In a sense, this book is a case study of developing the ActionBazaar application using EJB 3. Let's take a quick stroll around the ActionBazaar application to see what it's all about. 2.1 Introducing the ActionBazaar application ActionBazaar is a simple online auctioning system like eBay. Sellers dust off the treasures hidden away in basement corners, take a few out-of-focus pictures, and post their item listings on ActionBazaar. Eager buyers get in the competitive spirit and put exorbitant bids against each other on the hidden treasures with the blurry pictures and misspelled descriptions. Winning bidders pay for the items. Sellers ship sold items. Everyone is happy, or so the story goes. As much as we'd like to take credit for it, the idea of ActionBazaar was first introduced in Hibernate in Action by Christian Bauer and Gavin King (Manning, 2004) as the CaveatEmptor application. Hibernate in Action primary dealt with developing the persistence layer using the Hibernate object-relational mapping (O/R mapping) framework. The idea was later used by Patrick Lightbody and Jason Carreira in WebWork in Action (Manning, 2005) to discuss the open source presentation-tier framework. We thought this was a pretty good idea to adopt for EJB 3 in Action. This section will introduce you to the ActionBazaar application. You'll start with a subset of the architecture of ActionBazaar, and then you'll design a solution based on EJB 3. After this section, the rest of the chapter explores some of the important features of these technologies, using examples from the ActionBazaar application to introduce you to some of the EJB bean types and show how they're used with CDI and JPA 2. Let's begin by taking a look at the requirements and design of the example. www.it-ebooks.info 27 Introducing the ActionBazaar application 2.1.1 Starting with the architecture For the purposes of introducing EJB 3, let's focus on a small subset of ActionBazaar functionality in this chapter—starting from bidding on an item and ending with ordering the item won. This set of application functionality is shown in figure 2.1. The functionality represented in figure 2.1 encompasses the essentials of ActionBazaar. The major functionalities not covered are posting an item for sale, browsing items, and searching for items. We'll save these pieces of functionality for later. This includes presenting the entire domain model, which we'll discuss in chapter 9 when we start talking about domain modeling and persistence using JPA 2. The chain of actions in figure 2.1 starts with the user deciding to place a bid on an item. The user, Jenny, spots the perfect Christmas gift for her grandpa and quickly puts down a starting bid of $5.00. After the timed auction ends, the highest bidder wins the item. Jenny gets lucky and no one else bids on the item, so she wins it for the grand sum of $5.00. As the winning bidder, Jenny is allowed to order the item from the seller, Joe. An order includes all the items you've come to expect from online merchants—shipping information, billing details, a total bill with calculated shipping and handling costs, and so on. Persuasive Jenny gets her mom to foot the bill with her credit card and has the order shipped directly to her grandpa's address. Not unlike many e-businesses, such as Amazon.com and eBay, ActionBazaar doesn't make the user wait for the billing process to finish before confirming an order. Instead, the order is confirmed as soon as it's received and the billing process is started in parallel in the background. Jenny gets an order confirmation as soon as she clicks the Order button. Although Jenny doesn't realize it, the process to charge her mom's credit card starts in the background as she's receiving the confirmation. After the billing process is finished, both Jenny and Joe are sent email notifications. Having been notified of the Item Billing Place bid Bid end Order Item shipped Order confirmation Figure 2.1 A chain of representative ActionBazaar functionality used to examine a cross-section of EJB 3. The bidder bids on a desired item, wins the item, orders it, and instantaneously receives confirmation. Parallel with the order confirmation, the user is billed for the item. Upon successful receipt of