Thursday, March 14, 2013

Java EE 6 - Part 1 - Writing Stateless Session Beans

EJB 3.1 Session Beans types:
  1. Stateless - pooled instances 
  2. Stateful - dedicated instance to a client
  3. 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:
  1. Create an AccountCommon project.
  2. Create an AccountEJB project as EJB Module or EJB Appplication.
    1. Add a stateful session bean class - AccountBean.
    2. Select the AccountCommon project as the project in which to create the AccountBeanRemote interface definition. This is done automaticalrly by Netbeans 7.3.
    3. Add business methods to AccountBeanRemote interface in the AccountCommon project.
    4. 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;
    }
}


  1. Deploy the AccountEJB-ejb.jar to Glassfish v3 application server.
  2. 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:

Popular micro services patterns

Here are some popular Microservice design patterns that a programmer should know: Service Registry  pattern provides a  central location  fo...