How to create a Stateful Session Bean


A stateful session bean can store information between client calls, as opposed to stateless session beans that cannot remember anything about the user from its last call.
A stateful session bean looks like an ordinary Java class except that it is annotated with the @Stateful annotation.
The typical stateful session bean is a shopping cart which keeps track of items that the user has added duing it's visit to a particular site.
Below is an example of how a shopping cart stateful session bean could be declared:


package com.javadb.examples;

import javax.ejb.Stateful;

@Stateful(name="TheShoppingCart")
public class ShoppingCartImpl implements ShoppingCart {
    public ShoppingCartImpl() {
    }
}


As with a stateless session bean, the stateful session bean implements an interface - in this case the local interface that states what methods are to be implemented.
The stateful session bean may implement both local and remote interfaces. The local interfaces are used to call the bean within the same enterprise application.
The remote interface is used to call the session bean remotely, for example from another enterprise application located on another server or by a client application.
Below both interfaces are implemented. Note that we have added the annotations @Local and @Remote.


import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateful;

@Local({ShoppingCart.class})
@Remote({ShoppingCartRemote.class})
@Stateful(name="TheShoppingCart")

public class ShoppingCartImpl implements ShoppingCart, ShoppingCartRemote {
    public ShoppingCartImpl() {
    }
}


Business methods (read your methods) are then added to the Stateful Session Bean and the respective interfaces.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: