Avoid Emulating Entity Beans with Session Beans

Session beans that implement the SessionSynchronization interface (discussed in Chapter 14) can emulate some of the functionality of bean-managed entity beans. This approach provides a couple of advantages. First, these session beans, like entity beans, can represent entity business concepts; second, dependency on vendor-specific object-to-relational mapping tools is avoided.

Unfortunately, session beans were not designed to represent data directly in the database, so using them as a replacement for entity beans is problematic. Entity beans fulfill this duty nicely because they are transactional objects. When the attributes of a bean are changed, the changes are reflected in the database automatically in a transactionally safe manner. This is not possible in stateful session beans because, although they are transactionally aware, they are not transactional objects. The difference is subtle but important. Stateful session beans are not shared like entity beans. There is no concurrency control when two clients attempt to access the same bean at the same time. With stateful session beans each client gets its own instance, so many copies of the same session bean representing the same entity data can be in use concurrently. Database isolation can prevent some problems, but the danger of obtaining and using dirty data is high.

Another problem is that session beans emulating entity beans cannot have find methods in their home interfaces. Entity beans support find methods as a convenient way to locate data. Find methods could be placed in the session bean’s remote interface, but this would be inconsistent with the EJB component model. Also, a stateful session bean must use the SessionSynchronization interface to be transactionally safe, which requires that it be used only in the scope of the client’s transaction. This is because methods such as ejbCreate() and ejbRemove() are not transactional. In addition, ejbRemove() has a significantly different function in session beans than in entity beans. Should ejbRemove() end the conversation, delete data, or both?

Weighing all the benefits against the problems and risks of data inconsistency, I recommend that you do not use stateful session beans to emulate entity beans.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset