CHAPTER 1 INTRODUCTION TO THE EJB ARCHITECTURE Reusability EJBs are loosely coupled components.An EJB may be reused and packaged into multiple applications,though it must be bundled with,or have access to,the business interfaces of dependent EJBs Persistence Although no longer covered in th EJB spec,JPA entities are an essential complement to EJB.Entities are persistent byasngleovinthatiableidcnies.AaentiychsmapstoadatabaseabiEand objects enuty instance is represented Progression of the EJB Spec duced,it include s nev add or more importantly,sin e its firs ary of ho spec has progressec stcommercial implementations in1998 EJB 1.0 The initial release,1.0,be support for stateful and stateless rvice objects,called session beans;and optional rt fo sister ain obje and re ed the ng infra and pass-by-value sema antics. EJB 1.1 The follow-up release,1.1,mandated support among vendors for entity beans,and introduced the XMLdeployment descriptor to replace storing metadata in a special serialized class file. EJB 2.0 EJB 2.0 addressed the overhead and pass-by-value shortcomings of remote interfaces by introducing the local interface.Only clients running inside the J2EE container could access an EJB through its local interface,but pass-by-reference method calls allowed for more efficient interchanges between components.A new type of EJB was also introduced-the message-driven bean(MDB),which could participate in asynchronous messaging systems. Entity beans gained support for container-managed relationships(CMRs),allowing bean developers to declaratively specify persistent relationships between entity beans that were managed by the EJB container.Also,Enterprise JavaBeans Query Language(EJB QL)was introduced,which gave developers the ability to query entity bean instances using a language that resembled SQL. EJB 2.1 rvices,allov ngas sion b n to e an endpoint interfa and a timer service d EJBs to ejb-jar.xml ed EIB QL eployment descripto
Chapter 1 ■ Introduction to the EJB Architecture 4 Reusability EJBs are loosely coupled components. An EJB may be reused and packaged into multiple applications, though it must be bundled with, or have access to, the business interfaces of dependent EJBs. Persistence Although no longer covered in the EJB spec, JPA entities are an essential complement to EJB. Entities are persistent domain objects with unique identities. An entity class maps to a database table, and each entity instance is represented by a single row in that table. Progression of the EJB Spec Each time a new version of the EJB spec is introduced, it includes new, significant features to address popular demand and adopt emerging technologies. Here is a brief summary of how the EJB spec has progressed since its birth in 1996, or more importantly, since its first commercial implementations in 1998. EJB 1.0 The initial release, 1.0, began with support for stateful and stateless service objects, called session beans; and optional support for persistent domain objects, called entity beans. For portability, EJBs were made accessible through a special remote interface that offered portability and remotability, but incurred the overhead of a remoting infrastructure and pass-by-value semantics. EJB 1.1 The follow-up release, 1.1, mandated support among vendors for entity beans, and introduced the XML deployment descriptor to replace storing metadata in a special serialized class file. EJB 2.0 EJB 2.0 addressed the overhead and pass-by-value shortcomings of remote interfaces by introducing the local interface. Only clients running inside the J2EE container could access an EJB through its local interface, but pass-by-reference method calls allowed for more efficient interchanges between components. A new type of EJB was also introduced—the message-driven bean (MDB), which could participate in asynchronous messaging systems. Entity beans gained support for container-managed relationships (CMRs), allowing bean developers to declaratively specify persistent relationships between entity beans that were managed by the EJB container. Also, Enterprise JavaBeans Query Language (EJB QL) was introduced, which gave developers the ability to query entity bean instances using a language that resembled SQL. EJB 2.1 EJB 2.1 added support for Web Services, allowing a session bean to expose an endpoint interface, and a timer service that allowed EJBs to be invoked at designated times or intervals. EJB 2.1 also provided expanded EJB QL functions, and an XML schema was introduced as a replacement for the DTD that defined the ejb-jar.xml deployment descriptor
CHAPTER 1 INTRODUCTION TO THE EJB ARCHITECTURE EJB3.0 EJB 3.0 was a major milestone in the evolution of the standard.Introducing a new,simplified development model (see below).EJB components became POJOs(plain old Java objects);an EJB's bean class was no longer required to implement EJB-specific interfaces,and the properties that made a Java class an EJB were factored out into Java annotations or captured externally in the ejb-jar.xml deployment descriptor file.With a few basic conditions,any class could become an EJB and leverage the enterprise services offered by an EJB container. Also new in EJB 3.0,the Entity Beans portion of the spec was replaced by the new JPA spec and,consistent with the new simplified development model,JPA entities were POJOs as well.JPA entities were also decoupled from the EJB container and could be used independently of EJB,including in a pure Java SEenvironment. EJB 3.1 EJB3.1 further imp oduced in EJB3.0.The no erface option mer suppor t.EJB e su oset of the EJB Contai componen s an EJB 3.2 the Asy chronous and enha nced Timer featu sare added to the EJB Lite subset.Al s th be. and the rules g ing dec e been simp ry ed EJB 3 Simplified Development Model EJB 3.0 was a significant departure from earlier releases.The architects of EJB3 set out to redesign the development ntroduce a atly simplified development model that would reduce the co and.atth e same time incornorat e many of the ideas found in pee is in:the spec has been widely hailed as having achieved these goals,and in so doing has overcome many of the problems that prevented earlier versions of EJB from becoming widely adopted. XML and Annotations Ifyou are familiar with earlier versions of EJB,one of the first things you will notice in EJB 3 is that it is no longer necessary to capture EJB metadata in a deployment descriptor.EJB now lets you store your EJB metadata inside your bean source using Java annotations.This isn't to say that XMLdeployment descriptors have gone away;they are still alive and well,and many developers prefer them to annotations.Using XMLdecouples the Java source from the EJB metadata,allowing the same entity or enterprise bean classes to be used in different contexts,where the context-specific information is captured in the XML and doesn't"pollute"the bean class I prefer to view their EJB metadata directly in the context of their POJO classes and use an relig roponent self.A simple rule ),we sugge for you wve nee e uple our entity and bea ses from their El in XML.Or want to use t e entity cla ith ys mx a oth XMI wins.This allows any role(see the"EB Roles"section later in the char er)d mstream of the beande erride motadata sott ings without having to update the Java source,since ov rrides can be applied exclusively to the XMLdescriptors
Chapter 1 ■ Introduction to the EJB Architecture 5 EJB 3.0 EJB 3.0 was a major milestone in the evolution of the standard. Introducing a new, simplified development model (see below), EJB components became POJOs (plain old Java objects); an EJB’s bean class was no longer required to implement EJB-specific interfaces, and the properties that made a Java class an EJB were factored out into Java annotations or captured externally in the ejb-jar.xml deployment descriptor file. With a few basic conditions, any class could become an EJB and leverage the enterprise services offered by an EJB container. Also new in EJB 3.0, the Entity Beans portion of the spec was replaced by the new JPA spec and, consistent with the new simplified development model, JPA entities were POJOs as well. JPA entities were also decoupled from the EJB container and could be used independently of EJB, including in a pure Java SE environment. EJB 3.1 EJB 3.1 further improved upon the simplified development model introduced in EJB 3.0. The no-interface option was now supported for Local EJBs. The Singleton pattern was offered for Session beans along with Asynchronous and enhanced Timer support. EJB Lite—an embeddable subset of the EJB Container’s functionality—allowed EJB components to be executed in the same VM as an EJB client. EJB 3.2 In EJB 3.2, the Asynchronous and enhanced Timer features are added to the EJB Lite subset. Along with other improvements, the bean developer is offered more control over the transactionality of life-cycle interceptor methods, and the rules governing declaration of Local and Remote behavior have been simplified. EJB 3 Simplified Development Model EJB 3.0 was a significant departure from earlier releases. The architects of EJB 3 set out to redesign the development experience; to introduce a greatly simplified development model that would reduce the complexity of the enterprise beans themselves; and, at the same time, incorporate many of the ideas found in peer technologies. The consensus is in: the spec has been widely hailed as having achieved these goals, and in so doing has overcome many of the problems that prevented earlier versions of EJB from becoming widely adopted. XML and Annotations If you are familiar with earlier versions of EJB, one of the first things you will notice in EJB 3 is that it is no longer necessary to capture EJB metadata in a deployment descriptor. EJB now lets you store your EJB metadata inside your bean source using Java annotations. This isn’t to say that XML deployment descriptors have gone away; they are still alive and well, and many developers prefer them to annotations. Using XML decouples the Java source from the EJB metadata, allowing the same entity or enterprise bean classes to be used in different contexts, where the context-specific information is captured in the XML and doesn’t “pollute” the bean class. Many users, however, will prefer to view their EJB metadata directly in the context of their POJO classes and use annotations. To avoid wading into a religious war (vocal proponents on both sides abound), we suggest that you choose for yourself. A simple rule we follow is this: if we need to decouple our entity and bean classes from their EJB metadata, as when we want to use the same entity classes with two different entity inheritance strategies, we put our metadata in XML. Otherwise, we stick with annotations. Don’t forget—you can always mix and match, relying on the firm policy that whenever metadata is specified for an element using both XML and annotations, the XML always wins. This allows any role (see the “EJB Roles” section later in the chapter) downstream of the bean developer to override metadata settings without having to update the Java source, since overrides can be applied exclusively to the XML descriptors
CHAPTER 1 INTRODUCTION TO THE EJB ARCHITECTURE Note A more advanced strategy,which we also recommend,is to use annotations only when defining behavior on an enterprise bean oran entity that is truly integral to its definition,such as the relationship type of an entity relationship field,or the transactional requirements of a method on a session bean.Anything that could reasonably be overridden. such as the name of the table to which an entity maps,or the details of a value generator used for populating the primary key on an entity,would go in the XML descriptor,where it can be specified at deploy time by an application assembler, perhaps in consultation with a database administrator.While there is no harm in specifying default values using annotations in the Java source file,this approach recognizes the difference between firm metadata,which ought not to be modified,and loose metadata that may be freely modified without changing the behavior of the enterprise bean or entity. Dependency Injection After an EJB is instantiated inside the lava EE container,but before it is handed out to a client,the container may initialize property data on the instance according to rules defined for that enterprise bean.This feature is called dependency injection,and it is an example of inversion of control pattern,whereby an external provider initializes the properties of an object instance instead of by the class itself.EJB 3 introduced the use of dependency injection in Java EEand,aney because it caugnt on so well,his teatre has now been gver and the pec.he current dependency is managed through /S 30:Depen ncy Inje tionality is fu through /SR 346: cts and Depend ency injection for Java which cov Chapter 10,Contesa Depe ency Injection. Note Injection uses a"push"model to push data out to the bean,and it occurs regardless of whether the bean actually uses the data.if there is a chance that the data will not be used.the bean may elect to avoid incurrina the cost of the resource derivation by performing a Java Naming and Directory Interface(JNDI)lookup in Java code to"pull"the data,only if it is actually (or likely to be)used. Common examples of dependency injection use in EJB are as follows .Injecting an EntityManager into asession bean for interacting with entities in a persistence unit .Injecting a UserTransaction into a session bean that manages its transaction demarcation Interceptors:Callback Methods Both enterprise beans and entities may designate some of their methods,or methods on separate classes,to be called when certain life cycle events occur.For instance.a session bean may indicate that a certain method should be called after the bean has been instantiated,but before it has been handed off to a client.This method may initialize state information on the bean.or look up resources using INDI,or any other action it wishes,provided that it does not require a transactional context.Such callback methods are called interceptors,and they allow bean developers to participate programmatically in the interaction between an enterprise bean,or an entity,and its container. An important advantage of this pattern (also known as cross-cutting)is that a single interceptor may defined once and then applied to multiple methods,or even multiple EJBs. 6
Chapter 1 ■ Introduction to the EJB Architecture 6 ■ Note A more advanced strategy, which we also recommend, is to use annotations only when defining behavior on an enterprise bean or an entity that is truly integral to its definition, such as the relationship type of an entity relationship field, or the transactional requirements of a method on a session bean. Anything that could reasonably be overridden, such as the name of the table to which an entity maps, or the details of a value generator used for populating the primary key on an entity, would go in the XML descriptor, where it can be specified at deploy time by an application assembler, perhaps in consultation with a database administrator. While there is no harm in specifying default values using annotations in the Java source file, this approach recognizes the difference between firm metadata, which ought not to be modified, and loose metadata that may be freely modified without changing the behavior of the enterprise bean or entity. Dependency Injection After an EJB is instantiated inside the Java EE container, but before it is handed out to a client, the container may initialize property data on the instance according to rules defined for that enterprise bean. This feature is called dependency injection, and it is an example of inversion of control pattern, whereby an external provider initializes the properties of an object instance instead of by the class itself. EJB 3 introduced the use of dependency injection in Java EE and, largely because it caught on so well, this feature has now been given its own spec. The current dependency injection API is managed through JSR-330: Dependency Injection for JavaTM, and the functionality is further extended through JSR 346: Contexts and Dependency Injection for JavaTM EE 1.1, which we cover in Chapter 10, “Contexts and Dependency Injection.” ■ Note Injection uses a “push” model to push data out to the bean, and it occurs regardless of whether the bean actually uses the data. If there is a chance that the data will not be used, the bean may elect to avoid incurring the cost of the resource derivation by performing a Java Naming and Directory Interface (JNDI) lookup in Java code to “pull” the data, only if it is actually (or likely to be) used. Common examples of dependency injection use in EJB are as follows: • Injecting an EntityManager into a session bean for interacting with entities in a persistence unit • Injecting a UserTransaction into a session bean that manages its transaction demarcation Interceptors: Callback Methods Both enterprise beans and entities may designate some of their methods, or methods on separate classes, to be called when certain life-cycle events occur. For instance, a session bean may indicate that a certain method should be called after the bean has been instantiated, but before it has been handed off to a client. This method may initialize state information on the bean, or look up resources using JNDI, or any other action it wishes, provided that it does not require a transactional context. Such callback methods are called interceptors, and they allow bean developers to participate programmatically in the interaction between an enterprise bean, or an entity, and its container. An important advantage of this pattern (also known as cross-cutting) is that a single interceptor may defined once and then applied to multiple methods, or even multiple EJBs
CHAPTER 1 INTRODUCTION TO THE EJBARCHITECTURE POJO Implementation EJB 3 took great strides to eliminate the trappings that beset enterprise bean classes and their required interfaces in earlier EJB releases.Similar to complaints over having to define XML metadata to specify even the most basic bean behavior,developers found it burdensome to have to write custom interfaces to handle an enterprise bean's factory support,and inconvenient to require a session bean's interfaces to extend EJB-specific interfaces.All of these limitations were addressed in EJB 3. Home methods are no longer mandated,although they're still supported.For session beans and MDBs,a default constructor replaces the no-argument ejbCreate()method required by earlier EJB specs. For entities,the Home interface is replaced by an EntityManagerFactory instance that produces EntityManager instances for a JPA persistence unit to manage entity life-cycle operations,including query executio Intelligent Use of Defaults or declar marking a P ay rriding the default bel atch the ame is the @Table annotation re uired.Gr has been taken to ensure that the default value atch so that.in the maiority of use case plicit m etadata is not ed.leading to lea more clutter-free code. Note One consequence of relying on default behavior is that the class does not describe its full behavior anywhere so you need to have a good understanding of the default behavior that is being applied.IDEs can be useful in deriving and displaying the enterprise bean or entity with its fully defaulted values explicitly shown. Distributed Computing Model Essential to any enterprise application is the ability to execute tasks and run components in separate Java threads or processes.Through the RMI-based remoting services,clients in an application client tier may access EJBs running in an application server anywhere on the network.The pass-by-value behavior of remote interface methods provides a coarse-grained model designed to reduce network traffic between clients and servers that are loosely connected to each other.Many applications that use EJB do not require remote access,however,and elect to configure their EJBs for local use.This eliminates the overhead of remote access support while continuing to offer the remaining enterprise services EJB Roles The EJB spec defines seven roles for individuals involved in the different stages of defining an enterprise beanor entity,or in providing services and API implementation to enter nse beans. This book is targete at the three role ing ente nd the ciated meta .In practice se rol s may De and y one role an nd th oning of ta lopment proces s.We will refer to
Chapter 1 ■ Introduction to the EJB Architecture 7 POJO Implementation EJB 3 took great strides to eliminate the trappings that beset enterprise bean classes and their required interfaces in earlier EJB releases. Similar to complaints over having to define XML metadata to specify even the most basic bean behavior, developers found it burdensome to have to write custom interfaces to handle an enterprise bean’s factory support, and inconvenient to require a session bean’s interfaces to extend EJB-specific interfaces. All of these limitations were addressed in EJB 3. Home methods are no longer mandated, although they’re still supported. For session beans and MDBs, a default constructor replaces the no-argument ejbCreate() method required by earlier EJB specs. For entities, the Home interface is replaced by an EntityManagerFactory instance that produces EntityManager instances for a JPA persistence unit to manage entity life-cycle operations, including query execution. Intelligent Use of Defaults An excellent example of how EJB 3 simplifies the development process is its leveraging of default behavior to provide rich functionality with no coding or declarative metadata required. For instance, by simply marking a POJO with the @Entity annotation, all of its public properties automatically become persistent fields, and the table and column names take on derived values that match the entity and field names. Additional annotations or XML elements are only required when overriding the default behavior of a particular area. Only when the table name does not match the entity name is the @Table annotation required. Great care has been taken to ensure that the default values match the most common usages so that, in the majority of use cases, explicit metadata is not required, leading to leaner, more clutter-free code. ■ Note One consequence of relying on default behavior is that the class does not describe its full behavior anywhere, so you need to have a good understanding of the default behavior that is being applied. IDEs can be useful in deriving and displaying the enterprise bean or entity with its fully defaulted values explicitly shown. Distributed Computing Model Essential to any enterprise application is the ability to execute tasks and run components in separate Java threads or processes. Through the RMI-based remoting services, clients in an application client tier may access EJBs running in an application server anywhere on the network. The pass-by-value behavior of remote interface methods provides a coarse-grained model designed to reduce network traffic between clients and servers that are loosely connected to each other. Many applications that use EJB do not require remote access, however, and elect to configure their EJBs for local use. This eliminates the overhead of remote access support while continuing to offer the remaining enterprise services. EJB Roles The EJB spec defines seven roles for individuals involved in the different stages of defining an enterprise bean or entity, or in providing services and API implementation to enterprise beans. This book is targeted at the three roles involved in defining enterprise beans and their associated metadata. In practice, one or more of these roles may be performed by the same individual, and certain tasks may be performed by one role and overridden by another; but it is useful to understand the logical partitioning of tasks in the EJB development process. We will refer to these roles in various sections throughout the book
CHAPTER 1 INTRODUCTION TO THE EJB ARCHITECTURE The Enterprise Bean Provider The Enterprise Bean Provider,also known as the Bean Provider,has the onsibility of defining and implementing the bu ss logic and structure of an ente se bean.This includes def the lav thods,specifying transactional and security information declaratively on the be n and its methods,injection or lookup of re uired resources and anything else that can he anplied to the enternrise hean class Applied to JPA entities,the Bean Provider defines the persistent structure of the entity and its relationships with other entities.The provider may define mapping and primary key-generation behavior,but this role is generally limited to defining the logical dependencies and structure of the entity. The Application Assembler The Application As mbler combines EJBs into EJB modules and enti bines th r Jav modu s to pr n.This t olving the inte metadata d efin fo g re entty components :h ut need not The Deployer The Deployer takes an application that has been assembled by the Application Assembler and deploys it to a particular application server instance or cluster.The Deployer must resolve all of the external dependencies defined by the EJB component,mapping them to concrete resources installed in the application server environment.In the case of entities,the Deployer may provide or override the details of the live database objects to which the entities will map. How This Book Is Organized of each chapter.There is mple pro mpand thu ey may b ha toa term or c pt that is not defined in tha o that i was defined in an earlier ch apter of the book. Chapter 1:Introduction to the EJB 3 Architecture This chapter opens by introducing the book and offering an orientation to EJB.This orientation covers the EJB develonment framework and com oonent model,the core features of EJB,the history of EJB,the EJB 3 simplified development model,and the EJB distributed comp ting model.The chapter concludes with a"Getting Started" section to help you install the NetBeans IDE and GlassFish Java EE reference implementation server required to run the many sample applications provided with this book. Chapter 2:EJB Session Beans Chapter2 explores EJB's primary service object:the session bean.Session beans are examined in their many roles: as entity facades,as service components-both with and without state,as singleton or timer-driven objects,and as the primary orchestrators of transaction and security services. 8
Chapter 1 ■ Introduction to the EJB Architecture 8 The Enterprise Bean Provider The Enterprise Bean Provider, also known as the Bean Provider, has the responsibility of defining and implementing the business logic and structure of an enterprise bean. This includes defining the Java class, implementing service methods, specifying transactional and security information declaratively on the bean and its methods, injection or lookup of required resources, and anything else that can be applied to the enterprise bean class. Applied to JPA entities, the Bean Provider defines the persistent structure of the entity and its relationships with other entities. The provider may define mapping and primary key–generation behavior, but this role is generally limited to defining the logical dependencies and structure of the entity. The Application Assembler The Application Assembler combines EJBs into EJB modules and entities into persistence archives, and then it combines these modules together with other Java EE modules to produce an application. This task requires resolving references to logical server resources including references between EJBs. The Application Assembler must work with the interfaces and metadata defined for the EJB and entity components but need not be familiar with the implementation details. The Deployer The Deployer takes an application that has been assembled by the Application Assembler and deploys it to a particular application server instance or cluster. The Deployer must resolve all of the external dependencies defined by the EJB component, mapping them to concrete resources installed in the application server environment. In the case of entities, the Deployer may provide or override the details of the live database objects to which the entities will map. How This Book Is Organized To orient you to the structure of the remainder of this book, here is a brief summary of each chapter. There is no requirement that you read these chapters in order. Sample programs accompany each chapter, and they may be run independently of one another. Topics are introduced progressively, though, and thus if you find a reference in one chapter to a term or concept that is not defined in that chapter, chances are that it was defined in an earlier chapter of the book. Chapter 1: Introduction to the EJB 3 Architecture This chapter opens by introducing the book and offering an orientation to EJB. This orientation covers the EJB development framework and component model, the core features of EJB, the history of EJB, the EJB 3 simplified development model, and the EJB distributed computing model. The chapter concludes with a “Getting Started” section to help you install the NetBeans IDE and GlassFish Java EE reference implementation server required to run the many sample applications provided with this book. Chapter 2: EJB Session Beans Chapter 2 explores EJB’s primary service object: the session bean. Session beans are examined in their many roles: as entity facades, as service components—both with and without state, as singleton or timer-driven objects, and as the primary orchestrators of transaction and security services