What is the Session wraps Entity Pattern? What are the motivations behind it?

Dan Christopherson

This pattern is really just a quick way of saying "Clients access the system only through Session Beans, which encapsulate all details of the system's Entity Beans."

From my perspective, there are two primary motivations for this: to provide good transactional definition and improve performance, and to hide implementation details by providing a coarse-grained interface to the system.

As far as transaction definition and implementation goes, this pattern helps by allowing each call into the session beans to be a complete unit of work (AKA transaction). In J2EE based systems where the client calls entity beans directly either the client has to manage the transaction explicitely, or each call to an entity runs in its own transaction. In the first case (client managed transactions) we wind up with a lot of low-level exception handling code than we really want in application code. It becomes difficult to ensure that these exceptions are being handled correctly everywhere in an application (although good architecture can mitigate this risk). In the second case (each call running in its own transaction) performance will suffer greatly - most application servers will (by default) call ejbLoad at the beginning of each transaction and ejbStore at the end of each transaction. If you have 10 getter methods that must be called in a unit of work, that leads an incredibly slow system. Another reason that this 'naive' design is bad is that if you are modifying data, there is probably some set of data that the user expects to be modified as a unit (a unit of work). If you do not have some way of controlling transaction scope, and take the default of one transaction per call, you do not provide this ensurance to your users.

The second motivation is to hide implementation details and keep the system interface relatively narrow. In systems where this is important (and that's really any system with a projected lifetime of over 2 weeks 8^}) ), data that is displayed is usually extracted from the entity beans and put into 'View' classes by session beans. This gives you a narrow system interface (the session interfaces and View classes) while allowing you the modularity and cohesion benefits of a fine-grained implementation, as well as (possibly) the development time savings of CMP.