EJB3.1

S.M. Mahmudul Hasan shohan
      Software Engineer
     Therap Services LLC
What Is an Enterprise Bean
•   is a server-side component that encapsulates the business logic of an application.



• Beneits of Enterprise Beans
    –  EJB container provides system-level services to enterprise beans, the bean
      developer can concentrate on solving business problems.
    – the beans rather than the clients contain the application’s business logic, the
      client developer can focus on the presentation of the client.
    – , because enterprise beans are portable components, the application
      assembler can build new applications from existing beans.
When to Use Enterprise Beans
• The application must be scalable.
• Transactions must ensure data integrity.
• The application will have a variety of clients
Types of Enterprise Beans
• Session
  – Performs a task for a client; optionally may
    implement a web service
  – Stateless, Statefull, Singleton
• Message-Driven
  – Acts as a listener for a particular messaging
    type, such as the Java Message Service API
What Is a Session Bean?

• A session bean encapsulates business logic that can be invoked
  programmatically by a client over local, remote, or web service client
  views.
• In a stateful session bean, the instance variables represent the state of a
  unique client/bean session.
•   A stateless session bean does not maintain a conversational state with the client.
    When a client invokes the methods of a stateless bean, the bean’s instance
    variables may contain a state specific to that client but only for the duration of the
    invocation.
•   A stateless session bean can implement a web service, but a stateful session bean
    cannot.
•   A singleton session bean is instantiated once per application and exists for the
    lifecycle of the application
When to Use Session Beans

• Stateful session beans
   – The bean’s state represents the interaction between the bean
     and a specific client.
   – To hold information about the client across method invocations.
• Stateless session bean
   – has no data for a specific client.
   – performs a generic task for all clients.
   – implements a web service.
• Singleton session
   –   state needs to be shared across the application.
   –   to be accessed by multiple threads concurrently.
   –   to perform tasks upon application startup and shutdown.
   –   implements a web service.
Stateful Session Beans
• the instance variables represent the state of a unique client/bean session
• the client interacts with its bean
• often called the conversational state.
Life Cycle
• @PostConstruct
   – to initialize any resources such as database connection, files etc
     required for the bean.
• @PreDestroy
   – to release or close any resources used by the bean.


• Rules for @PostConstruct and @PreDestroy
   –   method signature must return a void and take no arguments.
   –   method should not throw Checked Exception
   –   can have access modifiers
   –   may be FINAL
Lifecycle

•   Passivation and Activation of Stateful Session Bean
     –   The transfer from the working set to secondary storage is called instance passivation. In contrast called
         activation.

•   Conditions for Passivation
     –   When the instance is not in a transaction.
     –   with an extended persistence context
     –   All the entities in the persistence context are serializable.
     –   The EntityManager is serializable.

•   @PrePassivate
     –   Invoked before the stateful session bean is passivated.
     –   can be used to release or close any resources used by the bean.

•   @PostActivate
     –   after the stateful session bean is activated.
     –   to re-initialize any resources such as database connection, files etc which are closed before passivation.
•   Rules for @PostActivate and @PrePassivate
     –   signature must return a void and take no arguments
     –   can have access modifiers
     –   cannot be STATIC or FINAL
Lifecycle
• The Lifecycle of a Stateless Session Bean



• The Lifecycle of a Message-Driven Bean
Lifecycle
•   The Lifecycle of a Singleton Bean
     – Same as Stateless bean




•   Initializing Singleton Session Beans
        @Startup
        @Singleton
        public class StatusBean {
        private String status;
              @PostConstruct
              void init {
                          status = "Ready";
              }
              ….
    }
• Managing Concurrent Access in a Singleton
  Session Bean
  – container-managed concurrency and bean-managed
    concurrency.

  @Lock(LockType.READ)
  @Lock(LockType.WRITE)
  @AccessTimeout
• Bean-Managed Concurrency
  – is responsible for ensuring that the state of the
    singleton is synchronized across all clients
Web Service
• annotated either the javax.jws.WebService or
  the javax.jws.WebServiceProvider
• must be annotated with javax.jws.WebMethod
• exposed to web service clients must have
  JAXB-compatible parameters and return type
• must have a default public constructor.
• must be annotated @Stateless.
Timer Service

• Creating Programmatic Timers
    – @Schedule or @Schedules

@Schedule(dayOfWeek="Sun", hour="0")
public void cleanupWeekData() { ... }
@Schedules ({
          @Schedule(dayOfMonth="Last"),
          @Schedule(dayOfWeek="Fri", hour="23")
})
• Canceling and Saving Timers
    – Timers can be cancelled by the following events.
    – When a single-event timer expires, the EJB container calls the associated timeout
      method and then cancels the timer.
    – When the bean invokes the cancel method of the Timer interface, the container
      cancels the timer.
Timers
• Canceling and Saving Timers
  – When a single-event timer expires, the EJB
    container calls the associated timeout method
    and then cancels the timer.
  – When the bean invokes the cancel method of the
    Timer interface, the container cancels the timer.
Message-Driven bean

• An application client that sends several messages to a queue.
• A message-driven bean that asynchronously receives and processes
  the messages that are sent to the queue




• The client starts by injecting the connection factory and queue
  resources:
• the client creates the connection, session, and message producer:
MDB
•   The Message-Driven Bean Class
     –   must be annotated with the @MessageDriven
     –   must be defined as public
     –   cannot be defined as abstract or final.
     –   a public constructor with no arguments.
     –   must not define the finalize method.
     –   implement the message listener interface for the message type it supports.
     –   @MessageDriven annotation typically contains a mappedName element that specifies the
         JNDI name of the destination from which the bean will consume messages

•   onMessage Method
     –   onMessage method of the MessageListener interface
     –   The method must be declared as public.
     –   The method must not be declared as final or static.
     –   The return type must be void.
     –   The method must have a single argument of type javax.jms.Message.

Ejb3.1 for the starter

  • 1.
    EJB3.1 S.M. Mahmudul Hasanshohan Software Engineer Therap Services LLC
  • 2.
    What Is anEnterprise Bean • is a server-side component that encapsulates the business logic of an application. • Beneits of Enterprise Beans – EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. – the beans rather than the clients contain the application’s business logic, the client developer can focus on the presentation of the client. – , because enterprise beans are portable components, the application assembler can build new applications from existing beans.
  • 3.
    When to UseEnterprise Beans • The application must be scalable. • Transactions must ensure data integrity. • The application will have a variety of clients
  • 4.
    Types of EnterpriseBeans • Session – Performs a task for a client; optionally may implement a web service – Stateless, Statefull, Singleton • Message-Driven – Acts as a listener for a particular messaging type, such as the Java Message Service API
  • 5.
    What Is aSession Bean? • A session bean encapsulates business logic that can be invoked programmatically by a client over local, remote, or web service client views. • In a stateful session bean, the instance variables represent the state of a unique client/bean session. • A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. • A stateless session bean can implement a web service, but a stateful session bean cannot. • A singleton session bean is instantiated once per application and exists for the lifecycle of the application
  • 6.
    When to UseSession Beans • Stateful session beans – The bean’s state represents the interaction between the bean and a specific client. – To hold information about the client across method invocations. • Stateless session bean – has no data for a specific client. – performs a generic task for all clients. – implements a web service. • Singleton session – state needs to be shared across the application. – to be accessed by multiple threads concurrently. – to perform tasks upon application startup and shutdown. – implements a web service.
  • 7.
    Stateful Session Beans •the instance variables represent the state of a unique client/bean session • the client interacts with its bean • often called the conversational state.
  • 8.
    Life Cycle • @PostConstruct – to initialize any resources such as database connection, files etc required for the bean. • @PreDestroy – to release or close any resources used by the bean. • Rules for @PostConstruct and @PreDestroy – method signature must return a void and take no arguments. – method should not throw Checked Exception – can have access modifiers – may be FINAL
  • 9.
    Lifecycle • Passivation and Activation of Stateful Session Bean – The transfer from the working set to secondary storage is called instance passivation. In contrast called activation. • Conditions for Passivation – When the instance is not in a transaction. – with an extended persistence context – All the entities in the persistence context are serializable. – The EntityManager is serializable. • @PrePassivate – Invoked before the stateful session bean is passivated. – can be used to release or close any resources used by the bean. • @PostActivate – after the stateful session bean is activated. – to re-initialize any resources such as database connection, files etc which are closed before passivation. • Rules for @PostActivate and @PrePassivate – signature must return a void and take no arguments – can have access modifiers – cannot be STATIC or FINAL
  • 10.
    Lifecycle • The Lifecycleof a Stateless Session Bean • The Lifecycle of a Message-Driven Bean
  • 11.
    Lifecycle • The Lifecycle of a Singleton Bean – Same as Stateless bean • Initializing Singleton Session Beans @Startup @Singleton public class StatusBean { private String status; @PostConstruct void init { status = "Ready"; } …. }
  • 12.
    • Managing ConcurrentAccess in a Singleton Session Bean – container-managed concurrency and bean-managed concurrency. @Lock(LockType.READ) @Lock(LockType.WRITE) @AccessTimeout • Bean-Managed Concurrency – is responsible for ensuring that the state of the singleton is synchronized across all clients
  • 13.
    Web Service • annotatedeither the javax.jws.WebService or the javax.jws.WebServiceProvider • must be annotated with javax.jws.WebMethod • exposed to web service clients must have JAXB-compatible parameters and return type • must have a default public constructor. • must be annotated @Stateless.
  • 14.
    Timer Service • CreatingProgrammatic Timers – @Schedule or @Schedules @Schedule(dayOfWeek="Sun", hour="0") public void cleanupWeekData() { ... } @Schedules ({ @Schedule(dayOfMonth="Last"), @Schedule(dayOfWeek="Fri", hour="23") }) • Canceling and Saving Timers – Timers can be cancelled by the following events. – When a single-event timer expires, the EJB container calls the associated timeout method and then cancels the timer. – When the bean invokes the cancel method of the Timer interface, the container cancels the timer.
  • 15.
    Timers • Canceling andSaving Timers – When a single-event timer expires, the EJB container calls the associated timeout method and then cancels the timer. – When the bean invokes the cancel method of the Timer interface, the container cancels the timer.
  • 16.
    Message-Driven bean • Anapplication client that sends several messages to a queue. • A message-driven bean that asynchronously receives and processes the messages that are sent to the queue • The client starts by injecting the connection factory and queue resources: • the client creates the connection, session, and message producer:
  • 17.
    MDB • The Message-Driven Bean Class – must be annotated with the @MessageDriven – must be defined as public – cannot be defined as abstract or final. – a public constructor with no arguments. – must not define the finalize method. – implement the message listener interface for the message type it supports. – @MessageDriven annotation typically contains a mappedName element that specifies the JNDI name of the destination from which the bean will consume messages • onMessage Method – onMessage method of the MessageListener interface – The method must be declared as public. – The method must not be declared as final or static. – The return type must be void. – The method must have a single argument of type javax.jms.Message.