List of Figures – EJB 3 in Action

List of Figures

Chapter 1. What’s what in EJB 3

Figure 1.1. EJB allows development of reusable components. For example, you can implement the credit card–charging module as an EJB component that may be accessed by multiple applications.

Figure 1.2. EJB as a framework provides services to EJB components.

Figure 1.3. EJBs are regular Java objects that may be configured using metadata annotations.

Figure 1.4. Most traditional enterprise applications have at least four layers. 1) The presentation layer is the actual user interface and can either be a browser or a desktop application. 2) The business logic layer defines the business rules. 3) The persistence layer deals with interactions with the database. 4) The database layer consists of a relational database such as Oracle that stores the persistent objects.

Figure 1.5. The component services offered by EJB 3 at each supported application layer. Note that each service is independent of the other, so you are for the most part free to pick the features important for your application. You’ll learn more about services in section 1.3.

Figure 1.6. Overall organization of the EJB 3 API. The Java persistence API is completely separable from the EJB 3 container. The business logic processing is carried out by through two component types: session beans and message-driven beans. Both components are managed by the container. Persistence objects are called entities, which are managed by the persistent provider through the EntityManager interface.

Figure 1.7. Java EE container typically contains web and EJB containers and a persistence provider. The stateless session bean (Credit Check EJB) and stateful session bean (Cart EJB) are deployed and run in the EJB container. Entities (Customer and Catalog) are deployed and run within an EJB persistence provider and can be accessed by either web or EJB container components.

Figure 1.8. Spring/EJB 3 integration strategy. It is possible to use EJB 3 business-tier components as if they were Spring beans. This allows you to use the complementary strengths of both technologies in a “hybrid” fashion.

Figure 1.9. Spring/JPA integration. Because JPA is a cleanly separable API, you can integrate Spring with JPA just as you would integrate Hibernate.

Figure 1.10. In certain cases, it might be a good idea to use Spring from EJB 3. Although it is possible to do so today, such support is likely to be much better in the future.

Chapter 2. A first taste of EJB

Figure 2.1. When you’re using JNDI, it’s the responsibility of the client to do a lookup and obtain a reference to the object. In EJB 3, you may think dependency injection is the opposite of JNDI. It is the responsibility of the container to inject an object based on the dependency declaration.

Figure 2.2. A chain of representative ActionBazaar functionality used to quickly 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 order confirmation, the user is billed for the item. Upon successful receipt of payment, the seller ships the item.

Figure 2.3. The ActionBazaar scenario implemented using EJB 3. From the EJB 3 perspective, the presentation layer is an amorphous blob that generates business-tier requests. The business-logic tier components match up with the distinct processes in the scenario—putting a bid on an item, ordering the item won, and billing the user. The billing MDB is triggered by a message sent by the order confirmation process. The business-tier components use JPA entities to persist application state into the database.

Figure 2.4. To make an otherwise overwhelming process manageable, the ActionBazaar ordering process is broken down into several steps. The first of these steps is to add one or more item to the order. The second step is to specify shipping information for the order. The third is to specify the billing information. Reviewing and confirming the order finishes the ordering process.

Figure 2.5. The Java EE “pony express” messaging model. Java EE adds reliability to messaging by adding a middleman that guarantees the delivery of messages despite network outages, even if the receiver is not present on the other end when the message is sent. In this sense, Java EE messaging has much more in common with the postal service than it does with common RPC protocols like RMI. We’ll discuss this model in much greater detail in chapter 4.

Figure 2.6. Asynchronously billing orders using MDBs. The stateful session bean processing the order sends a message to the order-billing queue. The billing MDB picks up this message and processes it asynchronously.

Figure 2.7. PlaceBidServlet invokes the addBid method of PlaceBid EJB and passes a Bid object. The PlaceBidEJB invokes the persist method of EntityManager to save the Bid entity into the database. When the transaction commits, you’ll see that a corresponding database record in the BIDS table will be stored.

Chapter 3. Building business logic with session beans

Figure 3.1. Parts of the PlaceBid session bean. Each session bean has one or more interfaces and one implementation class.

Figure 3.2. The lifecycle of an EJB starts when a method is invoked. The container creates a bean instance and then dependencies on resources are injected. The instance is then ready for method invocation.

Figure 3.3. Stateless session bean instances can be pooled and may be shared between clients. When a client invokes a method in a stateless session bean, the container either creates a new instance in the bean pool for the client or assigns one from the bean pool. The instance is returned to the pool after use.

Figure 3.4. Some ActionBazaar bid-related actions. While bidders can place bids and view the current bids on an item, admins can remove bids when needed. All of these actions can be modeled with a singe stateless session bean.

Figure 3.5. The chicken or the egg—the stateless session bean lifecycle has three states: does not exist, idle, or busy. As a result, there are only two lifecycle callbacks corresponding to bean creation and destruction.

Figure 3.6. Stateful bean session maintenance. There is a bean instance reserved for a client and each instance stores the client’s state information. The bean instance exists until either removed by the client or timed out.

Figure 3.7. The ActionBazaar bidder account creation process is broken up into multiple steps: entering username/password, entering biographical information, entering billing information, and finally creating the account. This workflow could be implemented as a stateful session bean.

Figure 3.8. The lifecycle of a stateful session bean. A stateful bean maintains client state and cannot be pooled. It may be passivated when the client is not using it and must be activated when the client needs it again.

Chapter 4. Messaging and developing MDBs

Figure 4.1. Basic MOM message flow. When the producer sends a message to the software, it is stored immediately and later collected by the consumer. Looks a lot like e-mail, doesn’t it?

Figure 4.2. ActionBazaar ordering before MOM is introduced. Slow B2B processing is causing customer dissatisfaction.

Figure 4.3. ActionBazaar ordering after MOM is introduced. Messaging enables both fast customer response times and reliable processing.

Figure 4.4. The PTP messaging model with one producer and two consumers

Figure 4.5. The publish-subscribe messaging model with one producer and three consumers. Each topic subscriber receives a copy of the message.

Figure 4.6. Anatomy of a message. A JMS message has a header, properties, and a body.

Figure 4.7. As soon as a message arrives at its destination, the container retrieves it and assigns a servicing MDB instance from the pool.

Figure 4.8. The MDB lifecycle has three states: does not exist, idle, and busy. There are only two lifecycle callbacks corresponding to bean creation and destruction; you can use PostConstruct and PreDestroy methods to receive these callbacks.

Chapter 5. Learning advanced EJB concepts

Figure 5.1. The “magic” of EJB. The container-generated EJB object receives all EJB client requests as the proxy, and reads configuration and inserts container services as required before forwarding client requests to the bean instance.

Figure 5.2. The EJB context interface has a subclass for each session and message-driven bean type.

Figure 5.3. Business interceptors are typically used to implement common code. The ActionBazaarLogger implements common logging code used by all EJBs in the ActionBazaar system.

Figure 5.4. The order in which business method interceptors are invoked. Default interceptors apply to all methods of all EJBs in an ejb-jar package. Class-level interceptors apply to all methods of a specific class. Method-level interceptors apply to one specific method in a class. Default application-level interceptors are invoked first, then class-level interceptors, then method-level interceptors.

Figure 5.5. How an EJB timer works. A client may invoke an EJB method which creates a timer that registers a callback in the EJB timer service. The EJB container invokes the timeout method in the bean instance when the timer expires.

Chapter 6. Transactions and security

Figure 6.1. Because the ordering process is not covered by a transaction, ActionBazaar reaches a strange state when a Snag-It order fails halfway through. The customer is essentially billed for a failed order.

Figure 6.2. Distributed transaction management. The application program delegates transaction operations to the transaction manager, which coordinates between resource managers.

Figure 6.3. The method invocations from the CMT session bean is actually forwarded to other session beans that may be using various transaction attributes.

Figure 6.4. A security breach in ActionBazaar allows a hacker to shill bids by posting an item, starting a bidding war from a fake account and then at the last minute canceling the highest fake bid. The end result is that an unsuspecting bidder winds up with an overpriced item.

Figure 6.5. Most common Java EE security management scenario using JAAS

Chapter 7. Implementing domain models

Figure 7.1. The core functionality of ActionBazaar. Sellers post items into searchable and navigable categories. Bidders bid on items and the highest bid wins.

Figure 7.2. Entities are objects that can be persisted in the database. In the first step you identify entities—for example, entities in the ActionBazaar domain.

Figure 7.3. The ActionBazaar domain model complete with entities and relationships. Entities are related to one another and the relationship can be one-to-one, one-to-many, many-to-one, or many-to-many. Relationships can be either uni- or bidirectional.

Figure 7.4. Inheritance support with entities. Bidder and Seller entities extend the User entity class.

Figure 7.5. A one-to-one relationship between the User and BillingInfo entities. A User may have at most one instance of the BillingInfo object and the BillingInfo object cannot exist without a User.

Figure 7.6. Every Item has one or more Bids where more than one Bid may be placed on an Item. Therefore, the relationship between Item and Bid is one-to-many whereas the relationship between Bid and Item is many-to-one.

Figure 7.7. The relationship between Category and Item is many-to-many because every category may have one or more items, whereas each item may belong to more than one category.

Chapter 8. Object-relational mapping

Figure 8.1. A unidirectional one-to-one (optional) relationship between User and BillingInfo

Figure 8.2. An entity can be mapped to more than one table; for example, the User entity spans more than one table: USERS and USER_PICTURES. The primary table is mapped using @Table and the secondary table is mapped using @SecondaryTable. The primary and secondary tables must have the same primary key.

Figure 8.3. Embeddable objects act as convenient data holders for entities and have no identity of their own. Address is an embeddable object that is stored as a part of the User entity that is mapped to the USERS table.

Figure 8.4. User has a one-to-one unidirectional relationship with BillingInfo. The User and BillingInfo entities are mapped to the USERS and BILLING_INFO tables, respectively, and the USERS table has a foreign key reference to the BILLING_INFO table. Such associations are mapped using @JoinColumn.

Figure 8.5. User has a one-to-one unidirectional relationship with BillingInfo. The User and BillingInfo entities are mapped to the USERS and BILLING_INFO tables, respectively, and the BILLING_INFO and USERS tables share the same primary key; the primary key of the BILLING_INFO table is also a foreign key referencing the primary key of the USERS table. Such associations are mapped using @PrimaryKeyJoinColumn.

Figure 8.6. The one-to-many relationship between the Item and Bid entities is formed through a foreign key in the BIDS table referring to the primary key of the ITEMS table.

Figure 8.7. Many-to-many relationships are modeled in the database world using join tables. A join table essentially pairs foreign keys pointing to primary keys on either side of the relationship.

Figure 8.8. The ActionBazaar user hierarchy. Each user type like Bidder and Seller inherit from the common User superclass. The empty arrow signifies there may be some other subclasses of the User class.

Figure 8.9. Storing all ActionBazaar user types using a single table

Figure 8.10. Modeling inheritance using joined tables. Each entity in the OO hierarchy corresponds to a separate table and parent-child relationships are modeled using one-to-one mapping.

Figure 8.11. The table-per-class inheritance strategy. Super- and subclasses are stored in their own, entirely unrelated tables.

Chapter 9. Manipulating entities with EntityManager

Figure 9.1. The EntityManager acts as a bridge between the OO and relational worlds. It interprets the O/R mapping specified for an entity and saves the entity in the database.

Figure 9.2. An entity becomes managed when you persist, merge, refresh, or retrieve an entity. It may also be attached when we retrieve it. A managed entity becomes detached when it is out of scope, removed, serialized, or cloned.

Figure 9.3. Transaction-scoped persistence contexts only keep entities attached within the boundaries of the enclosing transaction.

Figure 9.4. For an extended persistence context, once an entity is attached in any given transaction, it is managed for all transactions in the lifetime of the persistence context.

Figure 9.5. These relationships exist between various important classes in the javax.persistence package for using JPA outside the Java EE container.

Figure 9.6. Invoking the persist method on the EntityManager interface makes an entity instance managed. When the transaction commits, the entity state is synchronized with the database.

Figure 9.7. The Item entity is related to three other entities: Seller, Bid, and Category. The relationships to Item are many-to-one, one-to-many, and many-to-many, respectively.

Figure 9.8. An entity instance can be detached and serialized to a separate tier where the client makes changes to the entity and sends it back to the server. The server can use a merge operation to attach the entity to the persistence context.

Figure 9.9. The refresh operation repopulates the entity from the database, overriding any changes in the entity.

Figure 9.10. Entity listener execution order. Default entity listeners are executed first, then superclass and subclass listeners.

Chapter 10. Using the query API and JPQL to retrieve entities

Figure 10.1. The JPA query API includes EntityManager methods to create queries, the methods in the Query interface for executing the query, and the Java Persistence Query Language.

Figure 10.2. Each JPQL query is translated to a SQL query by the JPQL query processor and executed by the database. The query processor is supplied by the JPA provider, most likely the application server vendor.

Chapter 11. Packaging EJB 3 applications

Figure 11.1. Rules followed by application servers to deploy an EAR module. Java EE 5 does not require a deployment descriptor in the EAR module that identifies the type of modules packaged. It is the responsibility of Java EE container to determine the type of module based on its name (extension) and its content. It does so by following this algorithm.

Figure 11.2. The default class loaders used by Sun’s JVM. The bootstrap class loader (sometimes called the boot class loader) is at the top of the hierarchy and loads all platform classes.

Figure 11.3. The class loader by default follows Parent First Delegation model. When a class is required, it first asks its parent to load the class.

Figure 11.4. Illustration of class visibility of an EAR file containing multiple web modules, EJBs, and shared library modules. The EAR class loader loads the classes in the JARs packaged as library modules, and all classes loaded by the EAR class loader are visible to the EJBs. The classes loaded by EJB class loader are typically visible to the web module in most containers because the WAR class loader is a child of the EJB class loader.

Chapter 12. Effectively integrating EJB 3 across your application tiers

Figure 12.1. BidEAO is the interface for the EAO object. BidEAOImpl is the EAO class that implements the logic for CRUD operations for the Bid entity.

Figure 12.2. The Session Façade design pattern. Client applications may need to access entities or business logic remotely. JPA entities are POJOs and cannot be accessed remotely. You can use a session bean as a façade to the entities and consolidate the logic to manipulate entities in the session façade. Then, using other beans, you can let the clients access the session façade. A coarse-grained session façade also becomes a good candidate for being exposed as a web service.

Figure 12.3. Applying the Session Façade pattern to ActionBazaar. Using this pattern improves loose coupling between the client and the business-logic tier. If you access EJBs remotely using the Session Façade pattern, it reduces the number of RMI calls, thus improving application performance.

Figure 12.4. ActionBazaar application architecture. The ActionBazaar web module accesses the EJBs that implement the business logic and manipulate entities.

Chapter 13. Taming wild EJBs: performance and scalability

Figure 13.1. In pessimistic locking, when a user wants to update the data the underlying records are locked and no other user can perform any operation on the data. It is typically implemented using SELECT ... FOR UPDATE semantics.

Figure 13.2. How optimistic locking strategy is implemented by a persistence provider. If the locking mode is set to WAIT, the User2 would wait until User1 releases the lock.

Figure 13.3. You may use caching of objects at three levels: 1) the transactional cache, which is made available by the persistence provider within a transaction to reduce database round-trips; 2) the extended persistence context, which you can use as a caching mechanism with stateful session beans; and 3) the persistence unit level cache (if provided by the persistence provider), which is a shared cache that all clients of the persistence unit can use.

Figure 13.4. EJB(s) and web applications are collocated, and web applications use the local EJB interface to access the nearby EJBs.

Figure 13.5. EJB and web applications are in separate JVMs. Clients access EJBs using the remote interface via RMI. The same EJB application can be deployed to multiple servers.

Figure 13.6. The skeleton in the EJB server gives out a stub to the client. This stub is used by the client to communicate with the EJB remotely.

Figure 13.7. The stub that is downloaded by the client is instrumented with the load-balancing algorithm and has knowledge of the load-balancing servers.

Figure 13.8. Session state is replicated to other servers based on the server: 1) clients establish a session with a stateful bean in Server 2; 2) conversation state is replicated to Server 1 and Server 3 because state replication is enabled; and 3) if Server 2 crashes, the client gets routed to either Server 1 or Server 3 and there will be no loss in its state.

Figure 13.9. Distributed cache synchronization is used to synchronize the entity cache between two different Java EE containers.

Chapter 14. Migrating to EJB 3

Figure 14.1. It is possible to use EJB 3 beans as well as the JPA EntityManager in EJB 2 by looking them up from the JNDI context.

Figure 14.2. The changes necessary to migrate EJB 2 business interfaces to EJB 3. You do not have to extend EJB-specific interfaces or throw RMI or EJB exceptions in the methods.

Figure 14.3. The changes necessary to migrate EJB 2.x bean classes to EJB 3. You don’t have to implement EJB specific interfaces in EJB 3, and you don’t have to implement all required lifecycle methods, as in EJB 2.

Figure 14.4. While migrating EJB 2 entity beans to EJB 3, it is likely you’ll want to refactor to take advantage of features like OO inheritance support. In our example, the UserBean entity bean can be refactored into a User POJO entity superclass and Bidder, Seller, and so forth entity POJO subclasses.

Figure 14.5. The changes necessary to migrate JDBC DAOs to the EJB 3 JPA

Chapter 15. Exposing EJBs as web services

Figure 15.1. ActionBazaar built a web service and registered it in the UDDI registry. A client application searches the registry to find the service. The registry returns the WSDL registered by the service, and uses the WSDL to invoke the web service.

Chapter 16. EJB 3 and Spring

Figure 16.1. This ActionBazaar bidding module uses Spring with JPA. The Spring bean employs an entity access object to access the entities using JpaTemplate.

Figure 16.2. You can combine the power of Spring and EJB 3 by developing a Spring-enabled session bean. You can use the declarative transaction, security, and web services features of EJB 3 with the POJO injection and JpaTemplate features of Spring.

Figure 16.3. You can access a session bean from a Spring bean and reuse the business logic.

Appendix A. RMI and JNDI

Figure A.1. Communication between the RMI client and server (remote object). The RMI server binds an object in the RMI registry. The client performs a lookup in the RMI registry to get a reference to the remote object and then invokes the method on the remote object through the remote interface.

Figure A.2. JNDI provides a single unified API to access various naming services such as LDAP, NDS, NDS, NIS, RMI, and CORBA. Any naming service with a JNDI Service Provider Interface (SPI) provider can be plugged into the API seamlessly.

Figure A.3. An example JNDI tree for an application server. All global resources such as jdbc and jms are bound to the root context of JNDI tree. Each application has its own application context, and EJBs and other resources in the application are bound under the application context.

Appendix B. Reviewing relational databases

Figure B.1. Rows and columns in the CATEGORIES table. While columns store a domain of data, rows contain a record composed of a set of related columns in a table.

Figure B.2. The CATEGORY_ID foreign key in the ITEMS table points to the primary key of the CATEGORIES table.

Appendix E. Installing and configuring the Java EE 5 SDK

Figure E.1. The Java EE 5 SDK welcome screen

Figure E.2. The Java EE 5 SDK license screen

Figure E.3. The Select Installation Directory screen. Unless there is a reason not to do so, accept the defaults here.

Figure E.4. The admin configuration screen prompts you for server administration details.

Figure E.5. Some of the defaults on the Installations Options screen need to be changed.

Figure E.6. The Ready to Install screen summarizes all of the options you’ve selected so far.

Figure E.7. You will need to start the server from this screen before closing it.

Figure E.8. The application server administrative interface login screen

Figure E.9. Spend some time exploring the admin console.

Figure E.10. Select Start > Programs > Sun Microsystems > Application Server PE 9 > Start Java DB.

Figure E.11. The Derby DB startup command-line interface

Figure E.12. The output from the command-line Ant task that sets up the data sources and JMS resources necessary for the ActionBazaar application

Figure E.13. The output of running the deployed application for chapter 1

Figure E.14. The deployed application for chapter 1 in the admin console