THE EXPERT'S VOICE IN JAVA Beginning EJB 3 Java EE 7 Edition GET STARTED WITH ENTERPRISE JAVABEANS FOR YOUR ENTERPRISE APPLICATIONS Jonathan Wetherbee,Chirag Rathod,Raghu Kodali,and Peter Zadrozny N111F111111717722227- Apress
Contents at a Glance Ab0 ut the Authors… XX About the Technical Reviewer.......... ..xxiii Preface........ …Xxn Acknowledgments..... ....xxvii Chapter 1:Introduction to the EJB Architecture... .1 ■Chapter2:EJB Session Beans… 25 Chapter 3:Entities and the Java Persistence API........ 61 Chapter 4:Advanced Persistence Features........ 103 Chapter 5:EJB Message-Driven Beans...... .151 Chapter 6:EJB and Web Services............. 17n Chapter 7:Integrating Session Beans,Entities,Message-Driven Beans, and Web Services.......... .205 Chapter 8:Transaction Support in EJB. .239 Chapter9:EJB3 Performance and Testing... 281 Chapter 10:Contexts and Dependency Injection.. 305 Chapter 11:EJB Packaging and Deployment.... 329 Chapter 12:EJB Client Applications..... 347 Chapter 13:Testing in an Embeddable EJB Container. 395 Index..... …415 v
v Contents at a Glance About the Authors�������������������������������������������������������������������������������������������������������������� xxi About the Technical Reviewer ����������������������������������������������������������������������������������������� xxiii Preface ����������������������������������������������������������������������������������������������������������������������������� xxv Acknowledgments���������������������������������������������������������������������������������������������������������� xxvii ■Chapter 1: Introduction to the EJB Architecture ���������������������������������������������������������������1 ■Chapter 2: EJB Session Beans�����������������������������������������������������������������������������������������25 ■Chapter 3: Entities and the Java Persistence API������������������������������������������������������������61 ■Chapter 4: Advanced Persistence Features�������������������������������������������������������������������103 ■Chapter 5: EJB Message-Driven Beans �������������������������������������������������������������������������151 ■Chapter 6: EJB and Web Services����������������������������������������������������������������������������������177 ■Chapter 7: Integrating Session Beans, Entities, Message-Driven Beans, and Web Services ����������������������������������������������������������������������������������������������������������205 ■Chapter 8: Transaction Support in EJB��������������������������������������������������������������������������239 ■Chapter 9: EJB 3 Performance and Testing �������������������������������������������������������������������281 ■Chapter 10: Contexts and Dependency Injection�����������������������������������������������������������305 ■Chapter 11: EJB Packaging and Deployment ����������������������������������������������������������������329 ■Chapter 12: EJB Client Applications������������������������������������������������������������������������������347 ■Chapter 13: Testing in an Embeddable EJB Container���������������������������������������������������395 Index���������������������������������������������������������������������������������������������������������������������������������415
CHAPTER 1 ■■■ Introduction to the EJB Architecture When we set out to write this book,our goal was to present Enterprise JavaBeans(EJB)to developers,with a keer can be used in e hardcore power users alike.That's a large audience to satisfy and,as a reference guide,the EJB spec document covers it well.In writing a book about how to use EJB,we had to narrow our audience;nonetheless,we believe that we've written a book that will serve the needs of a majority of Java EE developers. This book is targeted at developers who are experienced with Java,have built single-or multi-tier applications using earlier versions of EJB or other technologies,and are ready to take on the challenges(and rewards)of building enterprise applications using standards-based technology.Recognizing that a combined 1,100 pages of reference material [covering the EJB and Java Persistence API(JPA)specs]can be daunting,we ha developers,unfolding EJB one section at a time,and giving you the information and code examples you need to roll. spec,but you will also lea arn throug out ho applicay of the co yo see hov ho fit int a bigger pict e.You ar ama2edoaew and ith ther th y the related APIs covered in this Web Services.and Contexts and Dependency miecti ion (CDD offer a lot with which to work.Once you're comfortable with the basics of building deploying and testing,you'll find that EJB components are not only po werful but also easy to build and use Together,the authors of this book have built a number of applications using EJB in concert with other technologies in the Java EE stack,and we have attempted to capture within it advice about the practical patterns we have learned,the strategies we have found successful,and some pitfalls you can avoid.Most chapters in this book are dedicated to exploring specific areas of EJB,but we have also included chapters on Java Persistence API(JPA). Contexts and Dependency Injection(CDI),Web Services,gauging the performance of your EJB applications,and deploying to the Java EE application server of your choice.An introductory"Getting Started"section at the end of this chapter will get you set up to run the many useful sample applications found at the end of each chapter in the book We hope this b ok will serve not only as a reference guide for information on EJB but also as a how-to guide and repository of practical examples to which you can refer back as you build your own applications.Enjoy! An Introduction to EJB In the late 1990s,as Java was bolstered by the emergence of separate technologies(such as RMI,TA,and CORBA)that ologies and o Over the ngyears,El as ev Ito encomp (while ju nd standa for deploying and executing business components n a distributed,multiuser environme
1 Chapter 1 Introduction to the EJB Architecture When we set out to write this book, our goal was to present Enterprise JavaBeans (EJB) to developers, with a keen eye toward how this technology can be used in everyday, real-world applications. JSR-345: Enterprise JavaBeansTM, Version 3.2 EJB Core Contracts and Requirements is a deep spec that addresses the needs of beginning developers and hardcore power users alike. That’s a large audience to satisfy and, as a reference guide, the EJB spec document covers it well. In writing a book about how to use EJB, we had to narrow our audience; nonetheless, we believe that we’ve written a book that will serve the needs of a majority of Java EE developers. This book is targeted at developers who are experienced with Java, have built single- or multi-tier applications using earlier versions of EJB or other technologies, and are ready to take on the challenges (and rewards) of building enterprise applications using standards-based technology. Recognizing that a combined 1,100 pages of reference material [covering the EJB and Java Persistence API (JPA) specs] can be daunting, we have provided an on-ramp for developers, unfolding EJB one section at a time, and giving you the information and code examples you need to roll up your sleeves and get to work. As each chapter unfolds, you will not only learn about a new area of the spec, but you will also learn through specific examples about how to apply it to your own applications. Many of these examples come directly from the comprehensive, end-to-end, Java EE Enterprise Wines Online application constructed in Chapter 7 and Chapter 12, so that you can see how they fit into a bigger picture. You are encouraged to take these examples and run with them. Try them out in your favorite IDE or development environment, and change them around and try new things. EJB and the related APIs covered in this book—JPA, Web Services, and Contexts and Dependency Injection (CDI)—offer you a lot with which to work. Once you’re comfortable with the basics of building, deploying, and testing, you’ll find that EJB components are not only powerful, but also easy to build and use. Together, the authors of this book have built a number of applications using EJB in concert with other technologies in the Java EE stack, and we have attempted to capture within it advice about the practical patterns we have learned, the strategies we have found successful, and some pitfalls you can avoid. Most chapters in this book are dedicated to exploring specific areas of EJB, but we have also included chapters on Java Persistence API (JPA), Contexts and Dependency Injection (CDI), Web Services, gauging the performance of your EJB applications, and deploying to the Java EE application server of your choice. An introductory “Getting Started” section at the end of this chapter will get you set up to run the many useful sample applications found at the end of each chapter in the book. We hope this book will serve not only as a reference guide for information on EJB but also as a how-to guide and repository of practical examples to which you can refer back as you build your own applications. Enjoy! An Introduction to EJB In the late 1990s, as Java was bolstered by the emergence of separate technologies (such as RMI, JTA, and CORBA) that addressed the enterprise needs of large-scale applications, a need arose for a business component framework that could unify these technologies and incorporate them under a standard component development model. EJB was born to fill this need. Over the ensuing years, EJB has evolved to encompass numerous features (while judiciously rejecting others), and it has matured into a robust and standard framework for deploying and executing business components in a distributed, multiuser environment
CHAPTER 1 INTRODUCTION TO THE EJB ARCHITECTURE What Is EJB? Each release of EJBi this ined by JSR 34 terprise Jo nce this pook dedicated largely to PA o areas complement ea The EJB 3.2 sp ntitled JSR 345:Enterprise JavaBeansM,Version 3.2 EJB Core Contracts and Requirements, together with the class library defined in the.2APl,define both a component model and a container framework. The EJB Component Model Asa component model,EJB defines three object types that developers may build and customize as follows operati transa d context beans (MDBs)are invoked asynchron nously in respons e to external events through cia on with a messaging queue or topic Complementing this,the Java Persistence API(JPA)principally defines the following persistent object type .Entities are objects that have unique identities and represent persistent business data. terp In EIR 3 managed by a persister nce provider andnatheEBContaineandhegyaenOlonge considered enterprise beans. The EJB Container The elb container provides the supporting environment in which elb components operate.This environment offers transaction and security services,pooling and caching of resources,component life-cycle services,concurrency support,and more-all of which we will explore throughout this book.EJB components specify the details of how they wish to interact with their supporting container using EJB-specific metadata that is either captured by the container and applied to the EJB's behavior at run time,or interpreted at the time an EJB component is deployed to an EJB container and used to construct wrapping. Core Features of the EJB Development Model Throughout its life,EJB has maintained its focus on delivering components imbued with a handful of core features. Declarative Metadata One of the hallmarks of the EJB component model is the ability for developers to specify the behavior of both enterprise beans and entities declaratively(as opposed to programmatically)using their choice of Java annotations and/or XML descriptors.This greatly simplifies the development process,since much customization can be added to a bean without ation code oice of both annotat 2
Chapter 1 ■ Introduction to the EJB Architecture 2 What Is EJB? Each release of EJB is managed through the Java Community Process (JCP) as a Java Specification Request (JSR). The latest release, which is covered in this book, is defined by JSR 345: Enterprise JavaBeansTM 3.2. EJB JSRs prior to EJB 3.0 covered Persistent components, but since the introduction of JPA, persistence is now managed through its own JSRs. Nonetheless, the two areas complement each other well, and we have included several chapters in this book dedicated largely to JPA. The EJB 3.2 spec, entitled JSR 345: Enterprise JavaBeansTM, Version 3.2 EJB Core Contracts and Requirements, together with the class library defined in the EJB 3.2 API, define both a component model and a container framework. The EJB Component Model As a component model, EJB defines three object types that developers may build and customize as follows: • Session beans can be stateless, stateful, or singleton, and they perform business service operations. These services may be declaratively configured to operate in distributed, transactional, and access-controlled contexts. • Message-driven beans (MDBs) are invoked asynchronously in response to external events through association with a messaging queue or topic. Complementing this, the Java Persistence API (JPA) principally defines the following persistent object type: • Entities are objects that have unique identities and represent persistent business data. Session and message-driven beans are EJBs, and they are often referred to collectively as enterprise beans. In earlier versions of EJB, entities were referred to as entity beans, and they also fell into this category. In EJB 3, however, entities are now managed by a persistence provider and not the EJB container, and they are no longer considered enterprise beans. The EJB Container The EJB container provides the supporting environment in which EJB components operate. This environment offers transaction and security services, pooling and caching of resources, component life-cycle services, concurrency support, and more—all of which we will explore throughout this book. EJB components specify the details of how they wish to interact with their supporting container using EJB-specific metadata that is either captured by the container and applied to the EJB’s behavior at run time, or interpreted at the time an EJB component is deployed to an EJB container and used to construct wrapping. Core Features of the EJB Development Model Throughout its life, EJB has maintained its focus on delivering components imbued with a handful of core features. Declarative Metadata One of the hallmarks of the EJB component model is the ability for developers to specify the behavior of both enterprise beans and entities declaratively (as opposed to programmatically) using their choice of Java annotations and/or XML descriptors. This greatly simplifies the development process, since much customization can be added to a bean without having to encumber the Java source with service implementation code. To accommodate developer preference and application flexibility, EJB offers developers their choice of both annotations and XML, with the ability to use both
CHAPTER 1 INTRODUCTION TO THE EJB ARCHITECTURE methods simultaneously within the same elb or entity.for specifving behavior in metadata.in cases where the same edence in resolving the conflict.Additional benefits of this appr this chapter. Configuration by Exception Coupled with the ability to specify behavior declaratively is the strong use of intelligent defaults in EJB.Much behavior is attached automatically to an EJB or an entity without it being declared explicitly,such as the transactional behavior of session bean methods and the names of the table and columns that map to an entity's persistent data properties. An annotation,or its counterpart in XML,needs to be specified explicitly only when non-default behavior is desired. In the most common cases,where the default behavior is leveraged,this approach leads to very sparse,clean code. This development model is known as configuration by exception,because only in exceptional(non-default)cases is it necessary to configure the behavior of the component explicitly. Scalability Large-scale applications demand the ability to scale well as the client load increases.The EJB server employs resource pooling to maximize object reuse,utilizes a persistence c objects,and implen re ent sy n(RD concurr s.The EJB cor ner also manages an EJB's life cycle allo wing dependent resources to e freed up and reused to opumize pertormance Location Transparency te access,allowing them to be acce ent, an ance transpar tly manage th ion details Transactionality The lava transaction apl(ta)defines a standard api for distributed transactions.and the eib container act ITA transac tion o EIBs.Since its inc managed the EJB spec has defined a standard model for declaratively specifying container on ente rise beans. Multiuser Security Method-level access control may be specified declaratively on EJBs,enforcing user-and role-level privileges defined by application server administrators. Portability Spec-compliant enterprise beans are deployable to any application server that implements EJB,at least in theory In practice(and this was particularly true ofreleases prior to EJB 3),vendors provided their own metadata definitions that enterprise bean developers grew to rely upon,locking them into a particular vendor's implementation.As EJB has matured,it has grown to incorporate many of these formerly platform-specific features,so that EJBs implemented today are far more portable than in the past
Chapter 1 ■ Introduction to the EJB Architecture 3 methods simultaneously within the same EJB or entity, for specifying behavior in metadata. In cases where the same piece of metadata is defined both in an annotation and in XML, the XML declaration takes precedence in resolving the conflict. Additional benefits of this approach are explored later, in the “EJB 3 Simplified Development Model” section of this chapter. Configuration by Exception Coupled with the ability to specify behavior declaratively is the strong use of intelligent defaults in EJB. Much behavior is attached automatically to an EJB or an entity without it being declared explicitly, such as the transactional behavior of session bean methods and the names of the table and columns that map to an entity’s persistent data properties. An annotation, or its counterpart in XML, needs to be specified explicitly only when non-default behavior is desired. In the most common cases, where the default behavior is leveraged, this approach leads to very sparse, clean code. This development model is known as configuration by exception, because only in exceptional (non-default) cases is it necessary to configure the behavior of the component explicitly. Scalability Large-scale applications demand the ability to scale well as the client load increases. The EJB server employs resource pooling to maximize object reuse, utilizes a persistence cache to avoid repeatedly querying or creating the same objects, and implements an optimistic locking strategy in the middle tier to reduce load on the relational database management system (RDBMS) and to avoid concurrency locking issues. The EJB container also manages an EJB’s life cycle, allowing dependent resources to be freed up and reused to optimize performance. Location Transparency EJBs may be configured for remote access, allowing them to be accessed across a network connection. A client, which may be another EJB, simply requests an instance of a remote EJB, and the local and remote EJB containers transparently manage the communication details. Transactionality The Java Transaction API (JTA) defines a standard API for distributed transactions, and the EJB container acts as a JTA transaction manager to EJBs. Since its inception, the EJB spec has defined a standard model for declaratively specifying container-managed transactional behavior on enterprise beans. Multiuser Security Method-level access control may be specified declaratively on EJBs, enforcing user- and role-level privileges defined by application server administrators. Portability Spec-compliant enterprise beans are deployable to any application server that implements EJB, at least in theory. In practice (and this was particularly true of releases prior to EJB 3), vendors provided their own metadata definitions that enterprise bean developers grew to rely upon, locking them into a particular vendor’s implementation. As EJB has matured, it has grown to incorporate many of these formerly platform-specific features, so that EJBs implemented today are far more portable than in the past