Meera has posted 70 posts at DZone. You can read more from them at their website. View Full User Profile

EJB 3 in Action

  • submit to reddit
Published by: Manning
ISBN: 1933988347

Reviewer Ratings




Buy it now

One Minute Bottom Line

When you start reading a technical book within the first few pages itself you really know whether you like the book or not. This book was very interesting to me and kept the interest all the way until the end. I found this book to be well worth the time I spent reading it in spite of me being quite familiar with EJB3 as well as JPA. If you are planning on using EJB3 or even migrating your existing EJB 2 applications, I would highly recommend this book.

Last but not the least, Part 4 and Part 5 of this book, and the performance considerations and best practices for EJB's at the end of a few chapters in itself is worth the price of the book.


Development of EJB was never easier and it became more complex with every release of EJB specification. The authors in this book have compared the three major releases with a ladybug, an elephant and finally a cow. It was very interesting to read this section and here are the 2 paragraphs from the book in case you're curious to know why?

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 will like being a cow the best because I will be loved by all and 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 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 just about as heavy as the largest of our beloved pachyderms. The brave souls who could not 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 is sacred for Hindus and respected as a mother whose milk feeds us well.

If you're new to EJB's and wondering why was the earlier versions of EJB ever compared to an elephant, here are a few of the limitations of EJB 2.x

  • To create a single EJB you had to create three source files (in some cases 5 if you're exposing remote interfaces as well) and also several XML deployment descriptors.
  • Several callback methods must be implemented that usually are never used.
  • Exception handling was a nightmare.
  • Unable to test outside the container. There were testing frameworks like Cactus and J2eeUnit, but using them wasn't easy either in automated builds.
  • EJB-QL was very difficult to use.

Part 1 Overview of the EJB landscape

Chapter 1 What's what in EJB 3 as per the authors this chapter gives you a 20,000-foot view of EJB3 from on board a hypersonic jet. This chapter also explains why you should consider using EJB3, and for programmers coming from EJB2, outlines the significant improvements EJB3 version offers.

Chapter 2 A first taste of EJB This chapter introduces the ActionBazaar application, the imaginary enterprise system developed throughout the book. Again as per the authors, this chapter is a low-altitude fly-over with a reconnaissance airplane which explores basic concepts such as metadata annotations, dependency injection. It also provides code examples of stateless session beans, stateful session beans, message-driven beans, and the EJB 3 Java Persistence API.

Part 2 Building business logic with EJB

Chapter 3 Building business logic with session beans. In EJB 3.0 session bean is a POJO managed by the EJB container. This chapter covers various session bean types in detail and describes the development of both stateless and stateful beans and their clients, with comprehensive examples of both types. The chapter also provides guidelines to help you decide whether to use stateless or stateful session beans.

Another interesting quote in this chapter was: If you think of a business system as a horse-drawn chariot with a driver carrying the Greco-Roman champion to battle, session beans are the driver. Session beans utilize data and system resources (the chariot and the horses) to implement the goals of the user (the champion) using business logic (the skills and judgment of the driver).

The authors also present a section which examines a few alternative strategies to implementing stateful business processing, as well as some issues you may need to consider when using them. The chapter ends with a section which provides some best practices for developing session beans.

Chapter 4 Messaging and developing MDBs covers basic messaging concepts, JMS, and covers MDB in detail. The chapter begins by introducing messaging concepts by briefly introducing MOM, show how messaging is used in our ActionBazaar application, and examines the two popular messaging models: point-to-point (PTP) messaging and publish-subscribe messaging.

In the next section, the authors provide an overview to JMS API by building a basic message producer by developing the ActionBazaar code that sends out the shipping request. The following section discusses the javax.jms.Message interface. The authors make an interesting analogy between the message parts and a mailing envelope.

The final section explores MDBs in detail, why you should consider using them, and how to develop them. The authors also discuss some best practices as well as pitfalls to avoid when developing MDBs.

Chapter 5 Learning advanced EJB concepts covers advanced topics such as dependency injection, interceptors, and timers. This chapter begins by providing a brief overview of EJB internals i.e. how the container provides the services behind the scenes and how to access environment information.

Both Spring and EJB 3.0 provide extensive support for dependency injection. Spring supports dependency injection based upon XML configuration files. On the other hand, EJB 3.0 supports dependency injection (e.g., EJBs and context objects) and any JNDI objects using simple annotations. In EJB 3.0 DI annotations are extremely short and easy to use.

In the next section you'll see how to use the @Resource annotation and its parameters. The difference between setter and field injection is well explained. You'll see the @Resource annotation in action to inject a variety of resources such as e-mail, environment entries, and the timer service. Finally, you'll learn how to look up resources using JNDI and the lookup method in EJBContext.

In the following section the authors cover the most exciting feature: the Interceptors which are lightweight AOP features in EJB 3 for dealing with crosscutting concerns. This section begins by explaining what's AOP? , what are interceptors, and by implementing logging using interceptors in a session bean in the ActionBazaar application. The last section in interceptors section explains how you can define lifecycle callbacks in interceptor classes in addition to business method interceptors.

The final section is about timer service which begins by explaining what are timers, using the timer service in the ActionBazaar application, and concludes by providing the merits and demerits of using EJB 3 timers.

Chapter 6 Transactions and security the first part of this chapter is dedicated to exploring the transaction management features of EJB3 and the authors in this part give an overview of transaction concepts, and transaction management using CMT and BMT. In CMT, you'll learn how to use @TransactionManagement and @TransactionAttribute annotations and the six choices for @TransactionAttribute annotation defined by enumerated type @TransactionAttributeType using the Snag-It ordering system of the ActionBazaar.

In the next sections, the authors redevelop the Snag-It ordering code using BMT, in which you'll learn about javax.transaction.UserTransaction interface. The final section in this part discusses the pros and cons of using BMT over CMT.

The next part deals with EJB 3 security features, in which you'll learn about both declarative and programmatic security support in EJB3. The first few sections in this part cover some basic security concepts like authentication and authorization, users, groups and roles. The next section explores how security is managed in EJB3 applications using both declarative and programmatic security. The security annotations covered in this part are: @DeclareRoles, @RolesAllowed, ,@PermitAll, @DenyAll and @RunAs.

Part 3 Diving into the Java persistence API (JPA)

Chapter 7 Implementing domain models covers domain modeling, a central concept in ORM. The chapter begins with a brief overview of domain modeling concepts: entities and relationships, followed by the ActionBazaar problem domain where the authors develop the core functionality of the ActionBazzar application. In the next few sections you actually begin implementing the domain model using JPA.

Chapter 8 Object-relational mapping the first part of this chapter briefly discusses the difference between the object-oriented and relational world, also known as "impedance mismatch", which occurs when trying to use a relational database management system from an object-oriented program.

The next section explores features of EJB 3 O/R mapping, which covers several ORM annotations such as @Table, @Column,@Enumerated, @Lob,@Temporal, and @Embeddable by using the ActionBazaar User entity. The authors explore mapping of all types of relationships in the next section: one-to-one, one-to-many, many-to-one, and many-to-many.

An important capability of the Java Persistence API is its support for inheritance and polymorphism, something that was not available in EJB 2.1.In the last section, you'll learn how entities can be mapped to database tables using different types of inheritance mapping strategies supported by JPA and compare their advantages and disadvantages:

  1. Single table : One table for all classes in the entity hierarchy
  2. Joined tables : One for the parent class, and each subclass has a separate table to store polymorphic properties
  3. Table per class : One table for each concrete class in the entity hierarchy

You'll also learn about polymorphic relationships.

Chapter 9 Manipulating entities with EntityManager. An EntityManager instance is used to manage the state and life cycle of entities within a persistence context. It is responsible for creating and removing persistent entity instances and finding entities by the entity's primary key. EntityManager also allows queries to be run on entities. In the first section, you'll learn about EntityManager interface and its methods.

In the next section, the authors explore how to create and use container-managed and application-managed EntityManagers. Container-managed EntityManagers are injected using the @PersistenceContext annotation and the authors show how to manage this using the ActionBazaar application. The later section shows how to use application-managed EntityManager which has nothing to do with a Java EE container, where you must write code to control every aspect of the Entity-Manager's lifecycle.

The following section explains about Entity lifecycle and CRUD operations. The authors also cover operations like flushing and refreshing.
The final section covers entity lifecycle listeners. The authors explore the use of entity callbacks using separate listener classes, default listeners, and the execution order of entity listeners if you have multiple listeners. The chapter concluded with a discussion of entity operations best practices

Chapter 10 Using the query API and JPQL to retrieve entities. The Java Persistence query language defines queries for entities and their persistent state. It is a database-independent, entity based query language. The JPQL is SQL like in its syntax, and if you know SQL, you know most of the JPQL syntax as well. It's an extension of EJB QL(EJB 2.x versions) and adds many more features which weren't available in EJB QL. Here is a screen shot from the book which gives you an idea about the same.

The chapter begins with an introduction to query API, followed by anatomy of a query and defining named queries. Then follows executing the queries, where the authors show how to create named or dynamic query instance and the actual execution of the query using the Query interface.

In the next few sections, they examine all aspects of executing a query: setting parameters, retrieving either a single entity or a list of entities, and setting vendor-specific query hints to improve query performance.

The final section discusses using regular SQL queries in EJB3. The authors concluded this chapter by saying "JPQL is the safest bet for writing queries, as it addresses the major limitations of EJBQL and is the only way to build applications that are portable across databases. Avoid using native SQL unless you have to use a vendor-specific feature."

Part 4 Putting EJB 3 into action

Chapter 11 Packaging EJB 3 applications begins with a discussions of application packaging and deployment by dissecting an ear file followed by discussing how an ear file is loaded by the application server.
All Java programmers should and must know how class loading works, right? Being familiar with class loading could save them several hours which otherwise would have been spent on debugging the two well-known exceptions: ClassNotFoundException, ClassCastException. In this section, the authors introduce the concept of class loading and look at the classloader hierarchy in an application server and then expose the parent delegation model. Finally, they examine class loading in Java EE and explore the dependencies between different modules.

In the next few sections the authors explain how to package all of the EJB types, including persistence entities. They also show how you can use descriptors to override settings specified in metadata annotations and also how to handle persistence modules and the various configurations required for a persistence unit, as well as O/R mapping with XML.

As with most chapters, the authors concluded this chapter with some best practices on packaging, and identify some common deployment issues that you may run into.

Chapter 12 Effectively integrating EJB 3 across your application tiers covers design patterns, accessing session beans from the web tier and packaging and using JPA from web applications.

The chapter begins with a section explaining some most important design patterns like the MVC patterns for the presentations tier, EAO pattern for the persistence tier and Session Façade pattern for the business logic tier.

The last section focuses on using JPA from the web tier. The authors cover all the three common scenarios of using JPA from the web tier:

  1. Using a container-managed entity manager in a Java EE 5 container
  2. Using an application-managed entity manager with a JTA transaction manager in a Java EE 5 container
  3. Using an application-managed entity manager with local transactions outside the container

Chapter 13 Taming wild EJBs: performance and scalability a must read chapter if you want to know how to performance tune your EJB 3 applications.

The chapter begins with entity locking issues, the various types of locking and than the authors focus on optimistic locking with JPA and show how you can obtain locks on entities using the EntityManager API. Note:JPA does not have support for pessimistic locking strategies. However, some persistence providers will have vendor-specific extensions to use pessimistic locking.

The next section covers improving entity performance by merging tables, dividing a table into multiple tables, and finally choosing the right inheritance strategy. The author's focus next on tuning the JDBC layer by using the following techniques: properly sizing the connection pool, caching SQL statements, using named queries and avoiding transactions for read-only entities.

Next follows reducing database operations by choosing the right fetch type, deferring database updates until the end of transactions, using DELETE_CASCADE appropriately and avoiding association tables in one-to-many relationships. In improving query performance the authors discuss some of the more common scenarios like avoiding full table scans, using indexes to make queries faster etc. The final section in improving entity performance, they cover caching and conclude this section by discussing caching best practices.

The authors next show several ways to improve the performance of EJB 3 components i.e. Session and Message-driven beans.

Part 5 Migration and Interoperability Issues

Chapter 14 Migrating to EJB 3 examines the major issues related to interoperability, compatibility, and migration to EJB 3. The authors show how you can mix-and-match EJB 2 and EJB 3 components in the same applications, as well as convert applications completely over to EJB 3.

They also provide guidelines for migrating each EJB 2 component to EJB 3.

This chapter also explains how to convert JDBC DAOs to use the EJB 3 JPA. Finally, the authors show the migration from existing O/R mapping frameworks to using the EJB 3 JPA.

Chapter 15 Exposing EJBs as web services begins with a quick review of a web service and its components, and discuss high-level approaches to web service development. If you are already familiar with all these concepts, you can easily skip these sections.

In the next section the authors briefly introduce the web services platform and then explain why you would choose EJB 3 session beans over POJOs.

Than comes the interesting section, developing EJB web services using JAX-WS 2.0. You'll learn how to expose a Stateless session bean as a web service using simple annotations. You start by using the @WebService annotation to convert the PlaceBid stateless EJB to a web service, and later see how to use @SOAPBinding annotation to specify the web service style. You'll also learn about other annotations, such as @WebMethod, @WebParam, @WebResult, @OneWay and @HandlerChain.

You exposed a web service, how about consuming one right? The authors show how to access a web service from an EJB such as a Session bean or Message-driven bean using the @WebServiceRef annotation to invoke the web service.

As I mentioned earlier, the chapter concluded with best practices for web service development.

Chapter 16 EJB 3 and Spring. The authors ask a question here, are you ready to get EJB 3 and Spring working together? If your answer to this is yes as was mine, than go ahead and read this chapter which I assure you is indeed interesting.

The first section introduces you to the Spring framework, benefits of Spring, IoC principle. If you are already familiar about the Spring framework you can skip this section. On the other hand, if you're new than this introduction isn't enough to know about Spring.

The following section explores how you can use Spring with JPA. The last section shows you the two ways you can combine EJB 3 components and Spring beans. First the authors show you about using Spring from EJB 3 components; then they show you how to access an EJB 3 session bean from a Spring bean.

Appendixes Appendix A is a tutorial on JNDI and RMI and appendix B provides a primer to databases. Appendixes C and D cover references to annotations and XML descriptors. The book also provides instructions on how to install and configure Java EE RI (Glassfish) and how to deploy the code samples in appendix E.

Published at DZone with permission of its author, Meera Subbarao.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)



Vadim Voituk replied on Tue, 2008/03/04 - 2:11am

Really nice book!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.