Thursday 22 September 2011

JavaEE: A beginner's guide to Enterprise Java Beans (EJB)

 EJB - is a managed, server-side component architecture for modular construction of enterprise applications. Simply EJB provide instrument to write business layer(logic) of your application.

There are three most used types of java beans:
1)Session  Beans
2)Mesage-drivien Beans
3)Entities

1)Session  Beans
There are three types of session beans: Stateful, Stateless and Singleton (till EJB 3.1). For Stateless and Stateful beans need to provide interfaces: remote and local. Remote beans are accessed via a network call and local beans are accessed within the same JVM.

Stateless - do not maintain states ex. charging credit card ; checking credit history


@Local
public interface StoreManagerLocal extends StoreManager {
    public List<Customer> findAllCustomers();
}

@Remote
public interface StoreManagerRemote extends StoreManager {
    public List<Customer> findAllCustomers();
}

@Stateless
@RemoteBinding(jndiBinding="AppStoreEJB/remote")
@LocalBinding(jndiBinding="AppStoreEJB/local")
public class StoreManagerBean implements StoreManagerLocal,StoreManagerRemote 
{
    @PersistenceContext(unitName="MyStore")
    private EntityManager em;
    
    @Override
    public List<Customer> findAllCustomers() {
        Query query = em.createQuery("FROM Customer");
        List<Customer> customerList = query.getResultList();
        return customerList;
    }

}

How to call:
public class Tester extends HttpServlet {
 private static final long serialVersionUID = 1L;
 
 @EJB(mappedName = "AppStoreEJB/local")  
 private StoreManager storeManager;

 //....
}

Stateful - saves bean state between client invocations ex. shopping cart on online shops.


@Stateful
public class ShoppingCart implements ShoppingCartLocal,ShoppingCartRemote
{
   //...
} 

Singleton - is a session bean with a guarantee that there is at most one instance in the application ex. loading common values for several objects till EJB 3.1

@Startup
@Singleton
public class StatusBean {
  private String status;

  @PostConstruct
  void init {
    status = "Ready";
  }
  //...
} 

2)Mesage-drivien Bean
-are business objects whose execution is triggered by messages instead of by method calls.( are stateless,server-side, transaction-aware components, for processing asynchronous JMS messages.)


@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/exampleQueue") })
public class MessageConsumer implements MessageListener {

    @Resource(mappedName = "java:/MySqlDS")
    private DataSource datasource;

    @Override
    public void onMessage(Message msg) {
        if (msg instanceof TextMessage) {
                TextMessage tmsg = (TextMessage) msg;
               logger.info("MESSAGE BEAN: Message received: " + tmsg.getText());
    }
} 

How to call:
    public static void main(String[] args) throws Exception {
        String destinationName = "queue/exampleQueue";

        Context ic = null;
        ConnectionFactory cf = null;
        Connection connection =  null;

        // need try, catch and close context
        ic = getInitialContext();  

        cf = (ConnectionFactory)ic.lookup("/ConnectionFactory");  
        Queue queue = (Queue)ic.lookup(destinationName);

        connection = cf.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  
        MessageProducer sender = session.createProducer(queue);

        TextMessage message = session.createTextMessage("Frank");   
        sender.send(message); 
        ic.close();
    } 

3)Entities
- represents persistent data maintained in a database.In EJB 3.0, Entity Beans were replaced by the Java Persistence API.

@Entity
@Table(name="customer")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="ID")
    private int id;

    @Column(name="COUNTRY")
    private String country;

//...
}
More details abouth Entities relationships in the next post.


References:
The Java EE 6 Tutorial - Enterprise Beans
JBoss AS 5 Development

3 comments: