Session Beans


In our discussion of overall design in and , we've considered how to decide when to use EJB, and the key services provided by the EJB container, such as container-managed transactions. In we examined entity beans and concluded that they are a questionable choice for data access in most cases; hence it is session beans that provide most of the value of EJB. In this chapter we'll take a deeper look at issues relating to implementing business logic with session beans. We'll begin by discussing the choice between stateless and stateful session beans. As we'll see, stateful session beans have significant disadvantages (principally concerning reliability and scalability in a clustered environment), meaning that stateless session beans should normally be preferred. We'll look at two important J2EE design patterns relating to session bean usage: the Session Façade pattern and the EJB Command pattern. The Session Façade pattern makes a session bean (usually a stateless session bean) the entry point to the EJB tier. This pattern is most important in distributed apps, for which session beans should provide the remote interface. Implementation details such as entity beans or Data Access Objects are concealed behind the session façade. Session beans may also be used to implement a web services interface. Some app servers already support this, and EJB 2.1 adds standard support for web services endpoints. In collocated apps, session beans are used to implement business interfaces where EJB container services simplify app code. In contrast, the EJB Command design pattern is based on moving code (rather than merely data) from client to EJB container. Although this pattern differs significantly from the more common use of session beans as façades, it is also implemented using a stateless session bean. We'll look in detail at container services affecting session beans, such as how an EJB container reacts when an EJB throws an exception, and the implications for implementing session beans; and how declarative transaction attributes can be used to ensure that CMT delivers the required behavior. We'll conclude by examining some good implementation practices when writing session beans.


In distributed J2EE app, use session beans to implement your app's use cases. In collocated apps, use session beans to implement business logic that can benefit from EJB container services. Stateless session beans should generally be used in preference to stateful session beans if there is a choice.