Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sessionscoped managed bean vs stateful ejb

If I have a @ManagedBean that's @SessionScoped, why would I use a @Stateful EJB? I used it before for shopping carts and maintaining a conversational state, but since a managed bean will be kept during the user session I can store state there, then call SLSB for bussiness logic. Is that correct? If it is, then stateful ejbs will be left for more specific applications such as when you need transactions etc?

like image 292
arg20 Avatar asked Jan 30 '11 09:01

arg20


1 Answers

Very often stateless session beans can be used for a lot of business problems.

Stateful does not necessarily means only a remote server keeps state, although this is certainly one of the options. A remote Swing client could first send a bunch of data to a stateful session bean, hold on to the stub and then subsequently send some commands that operate on this data. This saves the client from having to send the same (large amount of) data each and every time.

In the remote use case, it indeed somewhat mirrors the usage of the HTTP session when web clients (browsers) are used. The major difference is that the session is per bean here, while with the HTTP session, the session is a scope shared by many beans. Since the HTTP session is based on cookies, and cookies are global for a domain for the entire browser, the HTTP session can not directly support multiple sessions from the same client (e.g. per tab or per window). This is trivial with stateful session beans.

However...

Remote Swing clients talking to remote EJBs are not that common.

In the context you described in your question, you will typically use local EJBs and you will store most state in the HTTP session (be careful with sharing!) and these days in the view scope or conversation scope.

So, finally, when to use stateful session beans in this scenario?

One important use case is the extended persistence context in JPA. Normally with a transaction scoped entity manager, when an entity crosses the transactional boundary of an EJB method call it will be detached. If you want to (optimistically) lock an entity between user interactions, this is undesirable. You'll lose the lock.

With an extended persistence context, the entity remains attached and the locks valid when you return from a call to the stateful session bean. This is very useful for preview functionality to assure that nobody else has made any changes to the entity when you okay after the preview. Or indeed for a shopping cart where you want to assure that for some time the item can't be sold to anyone else while in the cart.

like image 131
Arjan Tijms Avatar answered Oct 09 '22 14:10

Arjan Tijms