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

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

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

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

public class StoreManagerBean implements StoreManagerLocal,StoreManagerRemote 
    private EntityManager em;
    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.

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

public class StatusBean {
  private String status;

  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;

    public void onMessage(Message msg) {
        if (msg instanceof TextMessage) {
                TextMessage tmsg = (TextMessage) msg;
     "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");   

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

public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;

    private int id;

    private String country;

More details abouth Entities relationships in the next post.

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