EJB 3.1 Session Beans types:
    
- Stateless - pooled instances
- Stateful - dedicated instance to a client
- Singleton - Only 1 instance per application per JVM instance
Following is some sample code for writing a stateful session bean (stateless is similar) - used Netbeans 7.3 with Glassfish v3 3.1.2:
- Create an AccountCommon project.
- Create an AccountEJB project as EJB Module or EJB Appplication.
- Add a stateful session bean class - AccountBean.
- Select the AccountCommon project as the project in which to create the AccountBeanRemote interface definition. This is done automaticalrly by Netbeans 7.3.
- Add business methods to AccountBeanRemote interface in the AccountCommon project.
- Implement those methods in the AccountBean class in AccountEJB project.
Project: AccountCommon
import javax.ejb.Remote;
/**
 * This is the Account remote interface.
 * 
 * @author rwatsh
 */
@Remote
public interface AccountBeanRemote {
    public double deposit(double amount);
    public double withdraw (double amount);
}
Project: AccountEJB
import javax.ejb.Stateful;
/**
 *
 * @author rwatsh
 */
@Stateful(name="AccountBean", mappedName="ejb/AccountBean")
public class AccountBean implements AccountBeanRemote {
    private double balance;
    @Override
    public double deposit(double amount) {
        balance += amount;
        return balance;
    }
    @Override
    public double withdraw(double amount) {
        balance -= amount;
        return balance;
    }
}
- Deploy the AccountEJB-ejb.jar to Glassfish v3 application server.
- Create an AccountClient Java EE application client which either looks up the AccoutBeanRemote interface using JNDI or has the container inject it at runtime using annotation @EJB. Invoke the business methods on the AccountBean.
Project: AccountClient
import com.rwatsh.ejb.AccountBeanRemote;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
 *
 * @author rwatsh
 */
public class Main {
    //@EJB 
    //private static AccountBeanRemote acc;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws NamingException {
        double balance;
        Context c = new InitialContext();
        AccountBeanRemote acc = (AccountBeanRemote)c.lookup("ejb/AccountBean");
        balance = acc.deposit(1000);
        System.out.println(balance);
        balance = acc.deposit(2000);
        System.out.println(balance);
        balance = acc.withdraw(500);
        System.out.println(balance);
    }
}
 
 
No comments:
Post a Comment