You are on page 1of 79

EJB 3.

Rajeev Gupta
M. Tech. CS

What we are going to cover


Overview

Session Beans
Stateless Stateful

Introduction to MDB

Session 1

Overview
Typical 4 tier architecture

Why EJB
EJB Containers Container Services Types of EJB and Introduction EJB use Cases

typical four tier architecture

typical four tier architecture


Most traditional enterprise applications have at least four layers.
1) The presentation layer is the actual user interface and can either be a browser or a desktop application. 2) The business logic layer defines the business rules 3) The persistence layer deals with interactions with the database.

4) The database layer consists of a relational

What is ejb?
EJB is component based framework for building

and deploying distributed applications

why we need it?


EJB as a framework provides services to the EJB

components

EJB as a container?
It provides a set of services basically start with

transaction security persistence Removing timer state managements Messaging etc

Without EJB overhead on the programmer to write all

above services EJB container is deployed on application server such as Jboss, Weblogic, glassfish etc. Programmer is only writing logic rest is provided by ejb container.

Type of bean
Session bean
Business Logic

Entity bean
Entity + Bean, called for persistence.... CMP(Container managed): Our container is going

to take care ... BMP(Programmer managed): A programme has to write jdbc code in entity bean to read /delete record
Message driven bean

What is Session Bean


Sesssion Bean
An EJB 3.0 or EJB 2.1 EJB component created by a

client for the duration of a single client-server session used to perform operations for the client.

Stateless o A session bean that does not maintain conversational state. Used for reusable business services that are not connected to any specific client. Stateful o A session bean that does maintain conversational state. Used for conversational sessions with a single client (for the duration of its lifetime) that maintain state, such as instance variable values or transactional state.

What is Entity Bean


Entity
An EJB 3.0 compliant light-weight entity object that

represents persistent data stored in a relational database using container-managed persistence. Because it is not a remotely accessible component, an entity can represent a fine-grained persistent object.

Entity Bean
An EJB 2.1 EJB component that represents persistent data

stored in a relational database

What is MDB
MDB
A Message-Driven Bean (MDB) is an EJB 3.0 or EJB 2.1

EJB component that functions as an asynchronous consumer of Java Message Service (JMS) messages.

Once upon a time . EJB 2.0


Services such as CheckInventoryEJB etc is to be

configured by two way


Programmatic declarative

Testing and deployment is not easy to create any type of bean in EJB 2.0 We have

some interface such as Remote, Home Interface and Local Interface and Whatever bean we are writing has to be implemented by ejb we are writing-Depandancy with the interface Bean are configured using xml files Clint for EJB 2.0 is Servlet, JSP, Applet etc

Diving into EJB 2.0

EJB 3.0
EJB provide configuration using annotation Development and testing is easy We have POJO based bean: don't require any

interface ;we can expose any normal bean as ejb bean Bean are configured using annotation EJB 3.0 don't have concept of entity bean, the entity bean is replaced by POJO based JPA In EJB 3.0 sun micro system comes with its own framework for ORM i.e. JPA(Annotation based) EJB 3.0 bean can be exposed as a web service can be called from .NET client

EJB Use Cases?


Example consider flight booking system(E

commerce application)
Browse Select Flight Address Details

Passport details
Credit card details Confirmation

Flight Booking system -------------------------------------------possible use cases.


Browse-Session Bean Select Flight-Session Bean Address Details-Session Bean Passport details-Session Bean Credit card details-Session Bean Confirmation-Entity bean

Use case for Message Driven Bean?


During X-max world wide the amazon.com

millions of order from one place to another ...i am in India and my friend in US... eBay provide on line ecommerce and ship to my friend... they have MILLIONS OF TRAINSACTION to complete

Order processing system

Mobile Activation

Session 2

Session Beans
Stateless session bean

Singletons
Stateful session bean Lifecycle and State Transitions

Stateless session bean

Stateless Session Beans


A stateless session bean does not maintain a

conversational state with the client ie Once the method is finished, the client-specific state should not be retained i.e. the EJB container destroys a stateless session bean
These types of session beans do not use the instance

variables,So they do not persist data across method invocation and therefore there is no need to passivates the bean's instance.
Because stateless session beans can support

multiple clients, they provide the better scalability for applications that require large numbers of clients.

The Lifecycle of a Stateless Session Bean


Because a stateless session bean is never

passivated, its lifecycle has only two stages:


nonexistent and 2. ready for the invocation of business methods.
1.

The Lifecycle of a Stateless Session Bean


The EJB container typically creates and

maintains a pool of stateless session beans, beginning the stateless session beans lifecycle. The container performs any dependency injection and then invokes the method annotated @PostConstruct, if it exists. The bean is now ready to have its business methods invoked by a client. At the end of the lifecycle, the EJB container calls the method annotated @PreDestroy, if it exists. The beans instance is then ready for garbage collection.

Lifecycle Callbacks for Stateless Session Beans

Addition of a new instance to the Stateless Session Bean Pool:

Retrieving reference to Stateless Session Bean business interface from JNDI

Servicing a business method

Removing the Stateless Session Bean instance

lifecycle event callbacks


The following lifecycle event callbacks are supported

for stateless session beans: PostConstruct


PostConstruct callbacks occur after any dependency

injection has been performed by the container and before the first business method invocation on the bean. PostConstruct methods are invoked in an unspecified transaction context and security context.
PreDestroy
PreDestroy callbacks occur at the time the bean

instance is destroyed. PreDestroy methods execute in an unspecified transaction and security context. NOTE. PostActivate and PrePassivate callbacks, if specified, are ignored for stateless session beans.

Hello world example Stateless session bean

Promise
package com.demo; import javax.ejb.Remote; @Remote public interface FirstDemoEJBRemote { public String testDemo(); }

Implementation.
package com.demo; import javax.ejb.Stateless; /** * Session Bean implementation class FirstDemoEJB */ @Stateless public class FirstDemoEJB implements FirstDemoEJBRemote {

public FirstDemoEJB() { // TODO Auto-generated constructor stub }


@Override public String testDemo() { // TODO Auto-generated method stub

return "testing session bean.........."; }


}

And the client


public class DemoTestEJBServlet extends HttpServlet { private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out=response.getWriter(); try { InitialContext ctx=new InitialContext(); Object obj=ctx.lookup("FirstDemoEJB/remote"); out.print(obj); FirstDemoEJBRemote remote=(FirstDemoEJBRemote)obj; String result=remote.testDemo(); out.print(result); } catch(Exception ex){ } } }

ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?> <ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:ejb="http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0"> <display-name>

DemoEJB </display-name>
</ejb-jar>

High level view

Low level view

Singleton Session Bean

The Lifecycle of a Singleton Session Bean


Like a stateless session bean, a singleton

session bean is never passivated and has only two stages, nonexistent and ready for the invocation of business methods

The Lifecycle of a Singleton Session Bean


The EJB container initiates the singleton session

bean lifecycle by creating the singleton instance. This occurs upon application deployment if the singleton is annotated with the @Startup annotation The container performs any dependency injection and then invokes the method annotated @PostConstruct, if it exists. The singleton session bean is now ready to have its business methods invoked by the client.
At the end of the lifecycle, the EJB container calls

the method annotated @PreDestroy, if it exists. The singleton session bean is now ready for garbage collection.

Stateful Session Bean

Stateful Session Bean


These types of beans use the instance variables that allows the data

persistent across method invocation because the instance variables allow persistence of data across method invocation.
The client sets the data to these variables which he wants to persist.

A stateful session bean retains its state across multiple method

invocations made by the same client. If the stateful session bean's state is changed during a method invocation, then that state will be available to the same client on the following invocation.
The state of a client bean is retained for the duration of the client-bean

session.
Once the client removes the bean or terminates, the session ends and

the state disappears.


Because the client interacts with its bean, this state is often called the

conversational state

Stateful Session Bean


A Stateful session bean is a session bean whose

instances can maintain the conversational state with the client. The conversational state of the stateful session bean, which describes the conversation between a specific client and a session bean, is contained in the fields of the stateful session bean.
Simply put, when you create a stateful bean an actual

instance is created by the container and dedicated to you and only you. Every call you make will go to your instance. Further, your instance will not be shared with anyone unless you give them a reference to your stateful bean. The instance will last until you remove it or until it times-out and is removed by the container

The Lifecycle of a Stateful Session Bean


The client initiates the lifecycle by obtaining a

reference to a stateful session bean. The container performs any dependency injection and then invokes the method annotated with @PostConstruct, if any. The bean is now ready to have its business methods invoked by the client.

The Lifecycle of a Stateful Session Bean


While in the ready stage, the EJB container may decide to

deactivate, or passivate, the bean by moving it from memory to secondary storage. (Typically, the EJB container uses a leastrecently-used algorithm to select a bean for passivation.) The EJB container invokes the method annotated @PrePassivate, if any, immediately before passivating it. If a client invokes a business method on the bean while it is in the passive stage, the EJB container activates the bean, calls the method annotated @PostActivate, if any, and then moves it to the ready stage. At the end of the lifecycle, the client invokes a method annotated @Remove, and the EJB container calls the method annotated @PreDestroy, if any. The beans instance is then ready for garbage collection. Your code controls the invocation of only one lifecycle method: the method annotated @Remove. All other methods in Figure are invoked by the EJB container.

Lifecycle Callbacks for Stateful Session Beans

Stateful session beans support callbacks for the lifecycle events: construction, destruction, activation, and passivation.

Retrieving reference to Stateful Session Bean business interface from JNDI

Servicing a business method

Passivating a Stateful Session Bean

Activating a Stateful Session Bean

Servicing a @Remove method

lifecycle event callbacks


PostConstruct
PostConstruct methods are invoked on the newly constructed instance, after

any dependency injection has been performed by the container and before the first business method is invoked on the bean. PostConstruct methods are invoked in an unspecified transaction and security context.
PreDestroy
PreDestroy methods execute after any method annotated with the Remove

annotation has completed. PreDestroy methods are invoked in an unspecified transaction and security context.
PostActivate
This notification signals the instance it has just been reactivated. Its purpose is to allow stateful session beans to maintain those resources that

need to be reopened during an instance's activation.


PrePassivate
This notification signals the intent of the container to passivate the instance. Its purpose is to allow stateful session beans to maintain those open

resources that need to be closed prior to an instance's passivation.


NOTE: The callbacks PreConstruct, PostDestroy, PreActivate, and

PostPassivate were not introduced because there did not seem to be use cases that justified their introduction.

Hello World Stateful Session Bean

account session bean


Account business interface package ejbExample.stateful; import javax.ejb.Remote; @Remote public interface Account { public float deposit(float amount); public float withdraw(float amount); @Remove public void remove(); }

AccountBean class
AccountBean class package ejbExample.stateful; import javax.ejb.Stateful; import javax.ejb.Remote; import javax.ejb.Remove; import javax.ejb.*; @Stateful(name="AccountBean") @Remote(AccountRemote.class) public class AccountBean implements AccountRemote { float balance = 0; public float deposit(float amount){ balance += amount; return balance; } public float withdraw(float amount){ balance -= amount; return balance; } @Remove public void remove() { balance = 0; } }

Life-Cycle Callback Methods


Methods in the bean class may be declared as a

life-cycle callback method by annotating the method with the following annotations:
javax.annotation.PostConstruct javax.annotation.PreDestroy javax.ejb.PostActivate javax.ejb.PrePassivate

Method Description
@PostConstruct Invoked by the container on newly constructed bean instances before the first business method is invoked on the enterprise bean and after all dependency injection has completed. @PreDestroy Invoked, when the bean is about to be destoryed by EJB container before removing the enterprise bean instance and after any method annotated @Remove has completed. @PostActivate Invoked by the container after the container moves the bean from secondary storage to active status. @PrePassivate Invoked by the container before the container passivates the enterprise bean, i.e. the container temporarily removes the bean from the environment and saves it to secondary storage.

Session 3

Message Driven Bean

The Lifecycle of a Message-Driven Bean

The Lifecycle of a Message-Driven Bean


The EJB container usually creates a pool of message-

driven bean instances. For each instance, the EJB container performs these tasks. If the message-driven bean uses dependency injection, the container injects these references before instantiating the instance. The container calls the method annotated @PostConstruct, if any. Like a stateless session bean, a message-driven bean is never passivated and has only two states: nonexistent and ready to receive messages. At the end of the lifecycle, the container calls the method annotated @PreDestroy, if any. The beans instance is then ready for garbage collection.

Lifecycle Callbacks for MessageDriven Beans

Addition of a new instance to the Message-Driven Bean pool

Servicing an onMessage(...) method

Removing the Message-Driven Bean instance

lifecycle event callbacks


The following lifecycle event callbacks are supported for

message-driven beans: PostConstruct


PostConstruct callbacks occur before the first message

listener method invocation on the bean. This is at a point after which any dependency injection has been performed by the container. PostConstruct callback methods execute in an unspecified transaction and security context.
PreDestroy
PreDestroy callbacks occur at the time the bean is removed

from the pool or destroyed. PreDestroy callback methods execute in an unspecified transaction and security context.
NOTE: PostActivate and PrePassivate callbacks, if

specified, are ignored for message-driven beans.

You might also like