Wrap Entity Beans with Session Beans

Discussions

J2EE patterns: Wrap Entity Beans with Session Beans

  1. Wrap Entity Beans with Session Beans (38 messages)

    A common EJB design pattern is to wrap entity beans with session beans. Here's some of the major arguments.

    1) Performance. Adding a session bean layer of abstraction above entity beans can actually improve performance. To see this, let's assume you have a web tier that accesses the EJB components across a network. If that web tier accessed entity beans directly, a network call would result for each entity bean access. But by wrapping the entity bean with a co-located session bean that provides bulk CRUD (Create Read Update Delete) access, the web tier can get more work done with a single network roundtrip.

    One way to see this is to draw an analogy between EJB and databases. Accessing a database row through a stored procedure allows you to perform one network roundtrip that results in many database operations that occur within the stored procedure.

    Entity beans are analogous to rows in a database, and session beans are analagous to stored procedures. Accessing a session bean that is co-located with an entity bean emulates accessing a row through a stored procedure.

    2) Reusability. The session bean layer is powerful because it externalizes all business logic from the entity beans. This means the entity beans contain data and data-related logic only. This promotes high re-use of entity beans. Likely what organizations should find is that the entity bean layer 'outlives' the session bean layer because their fundamental enterprise data does not change very often over time once defined properly up-front.

    3) A natural fit. I like to call this the 'verb-noun' paradigm. The session beans are your verbs (actions), and the entity beans are your nouns (people, places, and things). To me this is a natural form of programming.

    4) Data abstraction layer. The session bean layer is a facade. The particular way the session bean persists (via JDBC directly or via entity beans) is an implementation detail of the session bean. The decision about whether to use JDBC or entity beans can be deferred until a later date. And once a decision is made, things can change without affecting the entire application, because that nice session bean facade layer protects the web tier from any changes in the persistence layer.

    Here are some common arguments against this pattern:

    1) Loss of OO. People have argued that separating your sessions and entities results in loss of object-oriented programming features (specifically, the marriage of data and the logic that operates on that data). This is actually a half-truth.

    Indeed, entity beans can have logic, but they should contain data-related logic, such as logic to perform pre- or post-processing on the entity bean fields, rather than business logic.

    2) Performance. If the entities and sessions are already co-located in the same tier, there's no performance gain to the session wrapper layer. However, this is not a very sound argument because EJB systems should be developed irrespective of their particular deployment configurations.

    3) More code to write and maintain! Unless you have some automated way of dealing with the session beans, you do have to deal with that extra session bean code.

    -Ed

    Threaded Messages (38)

  2. Wrap Entity Beans with Session Beans[ Go to top ]

    Good article.

    We use the same pattern with CMPs with the CMPs returning value objects.

    PROS:
          DB errors are caught at compile time, not run time. This is a big win if you have to figure
    out oracle errors.

    CONS:
          CMPs are still pretty simple. They do not provide good OR-mapping capabilities.

    SOLUTION:
          We create DB VIEWS to map complex joins. Then CMPs are generated from these
    views.


    In general it's hard to image using Entities directly if your using JSPs. I guess the "manual joins"
    would have to be done in a JSP or in some other object that the JSP would know about.

    http://home.nycap.rr.com/hausam/EJBGen/EJBGen.html
    This tool was developed by a co-worker and is a good tool to generate CMPs from an existing
    SQL DB in a round trip environment. This tools is open sourced
  3. I think the most critical job of the session bean was left out of the above description. The session bean defines a transactional boundary. Consider this code in a JSP page that receives form information to update an Entity Bean:

    <P>Updating the Part info</P>
    //Update EJB
       MasterPart thePart = mpHome.findByPrimaryKey(key);
       if (thePart != null) {
           thePart.setGroup(group);
           //whoops something goes wrong...
    if (true) {
    throw new Exception("bad!");
    }
    thePart.setDescription(desc);
       }
     
    Unfortunately, having the JSP use the Entity directly would cause thePart to have the group updated (and committed), but the rest of the information would never have been updated, leaving it it in an inconsistent state.

    Michael
  4. I am very interested in accessing the tool that generates CMP beans but the link is dead. Is there a new link? Thank you.
  5. Wrap Entity Beans with Session Beans[ Go to top ]

    I agree with the performance and other stuffs. But if my entity has more number of fields is it OK to pass that many number of arguments into a session beans method?.

    If that is the case i feel the session bean will have some set of methods doing some specific jobs for an entify. That means we are going away from OO programming to C style programming. Because the users of the EJB's are not going to interact with Entity Beans. So they need not worry about how you are storing it into DB(either through Entity or direct DB call).

    Assume we are selling our EJB's to some one and they are programmers. So the targetted users won't feel comfortable with this design.

    Please correct me if I am wrong...

    Kaja
  6. Wrap Entity Beans with Session Beans[ Go to top ]

    Good point. I usually solve the problem by creating serializable proxy objects to represent the entity beans on the session bean interface. With this simplification, the benefits of session beans as process objects still outweigh those of direct entity bean access.
  7. The Wrap Entity bean with session bean concept is nothing but data modelling based upon Performance scenario.The OO Concept is not lost here.You can well implement all the properties of OOPS in your Entity and Session relationship.Session beans are not just as a wrapper to accept the aurguments only and pass those to entity beans...Entity beans are persistance and can represent one row of data in the table...where you can have your business logics in the calling method for entity beans before passing those to entity beans for persistance.

    I hope this helps..
  8. Is it possible to make an entity bean (or for that matter even a session bean) private only to a set of other EJBs. What i meant is making ejb e1 accessible only by ejbs e2, e3,e4 etc. e1 should not be accessed by any other ejb or client across the web tier.

    Any help would be greatly appreciated
  9. Wrap Entity Beans with Session Beans[ Go to top ]

    I still face a big problem having my Session EJB handles multiple Entity EJB. It happens when I need to know if somebody have changed my Entity EJB before I can change it. It is a Multi User access problem that I do not want to solve by "locking" my Entity EJB. I want a kind of listener or a publish/subscribe mechanism.
    I would prefer to put this mechanism in the Entity Bean because it is linked to the data.
    What do you think ?
    (A example of this problem is the modification of a purchase order by 2 people at the same time.)
  10. Vincent,

      The problem you describe is the classic dirty read problem. The way most people solve it is as follows. An entity bean contains a field with a number that gets incremented each time a change is made to the entity bean (sort of like a timestamp). So if two clients both get an entity beans data (its details object), then when the first client "sets" the details object back on the entity bean, this counter is incremented. Now when the second client tries to set the details object in the same entity bean (or purchase order), there is logic INSIDE THE ENTITY BEAN that sees that the client is coming back with stale data (an old timestamp), and throws an exception.

       This is the classic solution to the problem you speak of. The "staleness" tracking data is in the entityb ean, and the session beans know how to deal with the stale exception when thrown.

    hope this helps,

    Floyd
  11. Are you always guaranteed to do an ejbLoad after an ejbStore? ie. If you have multiple entity bean instances handling this and one of them takes care of incrementing the version number what is it exactly the synchronizes the version numbers and state in the other instances? Presumably this is the containers responsbility. So we can assume whenever an entity bean updates it's data all entity bean instances representing that primary key will consequently perform an ejbLoad to resynchronize their data right?
  12. well I think in your case you should have the isolation level set to serializable so that for the other person the screen opens in a read mode only
  13. Wrap Entity Beans with Session Beans[ Go to top ]

    The "loss of OO" problem with this pattern can get pretty bad, with all your objects flattened out into procedural-style code.
    In my experience this can be avoided by trying to follow the Facade pattern. If you keep the interface to the session beans as narrow as possible, with _exactly_ that minimum of methods the JSPs/Servlets actually require, the session beans won't look that bad.
  14. The "loss of OO" is not true. When we're dealing with coarse-grained objects, use case realization (the "business logic") and the business data should be very loosely coupled.

    In my opinion, the difference between behavior and data becomes very insignificant only in the case of fine grained objects. This is not always the case with server-side objects.

    In fact, if you consider maintainability, combining "nouns" and "verbs" proves to be very messy. Ivar Jacobson has discussed this in his classic book on OOSE.

    Subrahmanyam
  15. Wrap Entity Beans with Session Beans[ Go to top ]

    By wrapping Entity Beans with Session Beans, don't you put the whole purpose of your Entity Beans (as an encapsulation of business logic and data) into question? If you treat them as nothing more than representatives of a database table row, why not go to the database directly via the Session Beans?

    Regards, Michiel Perdeck
  16. Wrap Entity Beans with Session Beans[ Go to top ]

    Quite. This is almost the approach we've taken -- our stateless session beans interact directly with our domain objects, which in turn are made persistent using TOPLink. Works very nicely, and without the overhead associated with the use of entity beans.

    Tim
  17. But surely by doing this, you have created an old fashioned RPC applcation, where the stateless session bean methods become the global functions. Then you have to ask yourself where does that leave the OO skills, which are essential for anything but the smallest of projects IMHO. Or do you have some special twist?
  18. Those OO skills are still required -- in my experience, the most critical application of such skills is against the domain model. If you don't do a good job there of accurately representing your business, then nothing else is going to work. The service-level interfaces presented by EJBs (at least session EJBs) should be simple representations of whatever use cases the system is currently satisfying. If you are using some variant of the 'Value Object' pattern to represent data at the bean interface level, then all your nice domain object graphs are unfolded into pretty flat structure-like objects which are relatively easy to model anyway.

    I guess it depends on what parts of the EJB spec you are using: If you are using only stateless session beans to abstract and distribute your domain implementation and are using an O/R mapping tool to persist domain data, then you could achieve much the same effect with a Java CORBA implementation, albeit with a lot more hassle, a lack of serialization (OBV notwithstanding) and without all those nice handy deployment and packaging mechanisms. If, on the other hand, you wholeheartedly embrace the notion of entity beans and CMP etc., and it reliably works for you at the scale you need, then clearly the full EJB world is what your need.


    Tim
  19. You still need OO at the implementation level. Any large organization has similar functional interfaces (customer support, engineering etc.) in different locations and the best way to represent this is in an OO style so that requests can be routed according to the target object.

    Compare this with a pure functional interface as in CICS or Sybase Transaction Replication - you end up requiring procedures called do_this_in_tokyo, do_this_in_new_york etc.

    cheers
    alex
  20. Wrap Entity Beans with Session Beans[ Go to top ]

    So what is the ultimate advantage of using Entity EJBeans. As pointed out earlier we could as well use Java Objects with OR mapping tools like Toplink and use them with Session Beans. Here Session Beans would take care of Transaction requirements and Java Objects would take care of persistence. Is there any question of reusability involved here, kindly throw light on this.

    Amar

  21. I kinda agree on your question. The reusability part is more of a misnomer at the moment. Coupled to this we have the added problem of 1.1 CMP supporting no more than direct object to table mappings. Any serious enterprise deployment would require such features. That leaves us with the option of using BMP or some 3rd party O/R map tools.
    There is no support for complex relationships among entity beans( EJB 2.0 plans to solve this).But I think the real winner for 2.0 CMP Entity beans would be its ability to define complex relationships like aggregation and composition in a truly container-independant fashion.
  22. Hi!

    Tim says: "our stateless session beans interact directly with our domain objects, which in turn are made persistent using TOPLink. Works very nicely, and without the overhead associated with the use of entity beans. "

    Why does anybody use entity beans?
    (I assume concurrent users, security and transactions
    are managed by the session bean layer)

    regards

    Thorsten
  23. Unfortunatley Entity Beans aren't designed to encapsulate business logic. The general argument is that you'll tie your "General purpose" entity beans to a specific application by incorporating this kind of logic in them.
  24. Wrap Entity Beans with Session Beans[ Go to top ]

    I am confused. I thought that one of the most important advantage of EJB is that it is distributed. That means that I can move beans to a different container without changing a single line of code. But if we create such a wrapper session bean, the Entity bean and Session bean should always reside in the same container. If this session bean controls the transaction that involves multiple beans, then all these beans should reside in the same container. If we have a few such session beans that controls transactions for different combination of the given beans, then all these beans should reside in the container and they are no longer distributed Session and entity beans are talking to each other via sockets, and yet they are not distributed. Then why go with EJB at all? We can come up with more efficient reusable plain objects that perform transactional database access and don't have to talk to each other via sockets.
     I would greatly appreciate if somebody can clarify this issue.

    We had used it differently. We had created a plain class as a wrapper to an Entity Bean, that finds a reference to a home. If we need to perform a simple operation we call the Entity bean directly. If it is a unit of work - transaction, we do have session bean for that. However, session bean still does look up for app server, so our beans are distributed. May be we could keep our session beans more configurable, so they could become distributed upon demand.
    Alla
  25. Every thing is fine with this approach. I have a small clarification.

    The basic characteristic of the Session Bean is to make the business process synchronized. So, when a session bean is in the process of executing a business process, no other process can come into that part of the code. If entity bean is in the Wrapper of the session bean then If there are so many users of the session bean how the performance is increased.

    I have other doubt to clarify If session bean is for synchronization of the business then if a business process involves more users which is always possible in the web environment. The proformance of the session beans are questionned.

    Please clarify me if I am wrong.

    Ramagopal
  26. 1) Avoid long transactions -- keeping your transaction duration as short as possible will reduce problems resulting from contention for entity data.

    2) Have as many session beans available as you expect to have concurrent users of these beans and ensure that requests are spread evenly across them.

    Tim
  27. Wrap Entity Beans with Session Beans[ Go to top ]

    I 'm also using this pattern in my application. And I find it very good but I'm facing with a probem about it use.
    I would like to know if I it is better to have one Session bean per Entity bean, or if it's better to wrap a group of Entity with one Session Manager

    Meissa
  28. Meissa,

    "The Facade class provides a unified, simple interface to all of the clients of an application. Clients of the application use the Facade as "one-stop-shopping" for application functionality and data access. Meanwhile, it retains integration with the enterprise data model, since the Session Entity Facade is written in terms of enterprise beans." (from JPS1.01, design patters, downloadable from SUN)

    It is "better" (more logical) to wrap a group of entity beans with one session manager.
    E.G. Customer Session bean -> updates account, profile, orders, tasks.

    Mathias
  29. Wrap Entity Beans with Session Beans[ Go to top ]

    I use session beans as a facade to entity beans because
    (i) it allows me to put the logic in the session beans manipulating the entity beans
    (ii) if I'm returning a collection of 'value' objects to the client, it is far more efficient to use a single SQL query directly on the database than entity bean finder methods.

    In point (ii) above, I would welcome people's thoughts on how this squares with using CMP for entity beans. Using CMP makes it easy to go from one database to another and circumvent problems of clashing with DB keywords. However, in the session beans, the SQL statements will generally be hard coded - should I just read in the field names from the deployment descriptor using environment variables?

    -Paul
  30. Wrap Entity Beans with Session Beans[ Go to top ]

    One thing I don't understand is that why must it be a session bean. Why can we just use a plain class wrapper to be the facade of the entity beans?
  31. Wrap Entity Beans with Session Beans[ Go to top ]

    Lai,
      If you use a plain class wrapper you lose the advantage of reduced network traffic because your wrapper object would not be running in the ejb container with the entity beans.
    James
  32. James,
    What do you mean with reduced network traffic while explaining the disadvantages of using plain class wrappers instead of session facade.
    Thanks,
    Ilker
  33. Ilker,

    Each call from a plain class to the underlying Entity Bean would have to go over the network via RMI. As the Session bean is in the EJB container with the Entity Bean, it's calls to the Entity Bean would be local instead.

    Paul
  34. From the client perspective this it is great to work with the value objects. However, if the session is passing back lists of value objects then the system incurrs the overhead of loading and mapping the entire set when some of the members may never be used by the client. You may well eat up the savings in network traffic.

    //Geordie
  35. You speak nothing about concurrency issues. How do you plan to manage that? Where is that handled? by isolation levels? Would it be nice to be able to wrap Entity Beans with Session Beans that took care of concurrency issues? Assuming the public interfaces were via Session Beans only.

  36. Ed, thank you for your article. As I just read the comments to it, there still seem to be some open questions. Maybe this reply can help to clear them.

    The questions I will address are:
    1) Isn't deviding into Session Bean and Entity Bean a break with theory of OOP?
    2) Why not only doing Entity Bean or Session Bean / For what do I need an Entity Bean?
    3) How many Sessions Beans for Entity Beans? One for one?

    Let me just point out my point of view, which is a small extension to this pattern: For my projects, I often imagine the world I have to model as a set of active and passive objecte. Active objects do something with passive objects (verb and noun). Or more general: There are persons that work with things. This is a view that fits to most business processes, where you want to model the normal workflow, with living persons handling (dead) things (I often use the example of a person writing on a paper, what is most of business work even in computerized times). If you are modelling persons as Session Beans, and things as Entity Beans (using the wrapper pattern), this is easy to design and to implement, and you have all the benefits pointed out by Ed's article. With this in mind, let's now clear the questions that I saw that are open with the "Wrap Entity by Session" pattern:

    1) Isn't deviding into Session Bean and Entity Bean a break with theory of OOP?

    No, not at least. For in the real world there is no piece of paper that itself makes be written or drawn on (there always is some person that writes or draws, or that made a machine doing this for him), a complete snapshot of this scene would consist of at least two objects, the paper and (!) the writer (not "or"). So on the contrary, this seems to me even more (!) object oriented as combining what to write (data) and how to write (method) into one single object, either the entity bean or the session bean.

    2) Why not only doing Entity Bean or Session Bean / For what do I need an Entity Bean?

    This has several groups of reasons, of what I only will tell one point each, because most of the points have been very good pointed out by other writers before (see discussion board): a) OOP reasons (see above): As I wrote, in the real word it is not possible that a peace of paper writes on itself (what theDocument.setText(newText) directly used from the client application would be), and also there cannot be a writer that writes something without having a piece of paper (or something else) to write on (what theWriter.setText(String newText) would be); so there would not be a complete snapshot of the scene if modelled with one object only, either EB or SB. You always need both objects to model the whole scene (what theWriter.writeOnPaper(Paper thePaper, String newText), which would be implemented as thePaper.setText(newText), would be). b) Technical reasons: e. g., think of one container demarcated transaction in that you want to use many entity methods - this is easily done with a SB's method calling the EB's methods, and the appropriate flag in the deployment descriptor, when we use the wrapper pattern. Try to do this with an enity bean only, and you need to use client demarcated transactions. Try to do this with the SB only, and you will need to do BMP (for I do not know a working CMP that can build many table wrappers into a SB). c) Reusing: Think of your document as an aggregate that consists of the wrappers of ten different database tables. The entity bean is a good place for building an aggregate that hides this complexity; anyone can reuse this object easily. This would also work with SBs you may think, but do you really want to carry the burden of all special workflow processing methods that someone implemented into that bean, that you do not know and that you do not need at all, when all what you want to have is a wrapper for that tables?
    Sure there are many of other good reasons to use the pattern, and as I mentioned, most of them are written down on the discussion board.

    3) How many Sessions Beans for Entity Beans? One for one?

    As in the real world any passive (dead) object can be used by a lot of active (living) objects (persons) - think of a group of people writing on the same blackboard - and there also may be one person that uses many objects (think of one user that has the ability not only to write on that blackboard but also to use a computer keyboard to type his ideas into his machine), it is clear that only in simple scenes there is a one to one relationship between SB and EB. In most cases there will be a one to many (in either direction) or many to many relationship, and moreover, this relations will be undetermined, what means that you as the developer of either the used SB or EB, cannot rely on "the other object" is there for you exclusively. That means, always think of reusing in both directions, and keep in mind that if you develop one SB that uses one EB, that in future there may be a developer that e. g. writes a SB that uses the same EB.

    In abstract, it's all a question of not only dealing with EJB terminology and patterns, but thinking of the world as it really is. Most of the problems discussed are not EJB-specific, but have a representation in the real world. I hope that this view on EJB will give an answer to some of the questions, and I would be glad if someone likes to discuss this.
  37. Wrap Entity Beans with Session Beans[ Go to top ]

    This is what I like to call the "take some data, do something with it, and move it over here" approach.

    The session facade pattern creates global functions. The entity beans represent the tables. In the session beans we write code that edits the data in the tables.

    What's wrong with this picture? Nothing. But we can do better. OOAD encourages us to model the problem domain into static class structure, sequence diagram, statechart, etc. Then we end up with a mix of objects. Some are mostly behavior with little state, some are mostly state with little behavior, some are a mixture of both. Trying to set dogmatic standards for noun and verb content in objects is counterproductive. However, imposing a limitation that requires objects to be either state (entity) or behavior (session) limits our expressive power. We are then unable to implement solutions.

    I think that object data management systems offer the best ability to provide persistence capabilities to object-oriented systems. That way you model the objects (it might just be a person writing on a paper, although I'm sure the person has at least some state) and you get persistence for free. Try objectstore, you'll never look at EJB's the same again.

    Dan
  38. Wrap Entity Beans with Session Beans[ Go to top ]

    With local references in the 2.0 draft 2 there can be significant performance gains since the session calls to entities can be local. Thus some scenarios may be client invoking on session (network call), session invoking on entity1 (local), session invoking on entity2 (local(, etc.
    Whereas without the session facade, the client must invoke network calls on all these entities in a workflow say.
  39. Wrap Entity Beans with Session Beans[ Go to top ]

    John,

    I will agree with you absolutely. If a Session bean method call is not local to Entity bean method there will be over head in marshalling and unmarshalling data even if these beans lie in one application jar/JVM/Application Server. Please correct me if i am wrong.

    Thanks,
    Srini