• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
JEE Course - EJB
 

JEE Course - EJB

on

  • 5,791 views

The

The

Statistics

Views

Total Views
5,791
Views on SlideShare
5,791
Embed Views
0

Actions

Likes
1
Downloads
189
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    JEE Course - EJB JEE Course - EJB Presentation Transcript

    • Enterprise Java Beans Copyright © Oded Nissan 2009
      • Overview
      • Session Beans
      • Security
      • Dependency Injection
      • Message Driven Beans (MDB)
      • Transactions
      • EJB Design Patterns
      • Java Persistence API (JPA) Overview
      • Summary
      Enterprise Java Beans Copyright © Oded Nissan 2009
    • Overview Copyright © Oded Nissan 2009
    • The JEE Platform Copyright © Oded Nissan 2009
      • A server side component performing the business logic of an application.
      • Built-in support for transactions, security and distribution.
      • Support for both synchronous and asynchronous invocation.
      What is an EJB ? Copyright © Oded Nissan 2009
      • Distributed components
      • Transaction management support
      • Security
      • Scalability and fail-over
      • Asynchronous
      • Persistence – object relational mapping.
      EJB Features Copyright © Oded Nissan 2009
      • Leverages the benefits of component-model on the server side
      • Separates business logic from system code
        • Container provides system services
      • Provides framework for portable components
        • Over different JEE-compliant servers
        • Over different operational environments
      • Enables deployment-time configuration
        • Deployment descriptor
      EJB Advantages Copyright © Oded Nissan 2009
      • You should consider using enterprise beans if your application has any of the following requirements :
      • The application must be scalable. To accommodate a growing number of users, you may need to distribute an application’s components across multiple machines. Not only can the enterprise beans of an application run on different machines, but also their location will remain transparent to the clients .
      • Transactions must ensure data integrity. Enterprise beans support transactions, the mechanisms that manage the concurrent access of shared objects .
      • The application will have a variety of clients. With only a few lines of code, remote clients can easily locate enterprise beans. These clients can be thin, various, and numerous .
      When to use EJB ? Copyright © Oded Nissan 2009
      • Stateless Session Beans
      • Stateful Session Beans
      • Message Driven Beans – Asynchronous.
      • Entities – Persistent. (part of the JPA spec).
      EJB Types Copyright © Oded Nissan 2009
    • Session Beans Copyright © Oded Nissan 2009
      • A session bean is a business service that resides on the server.
      • The client invokes the session bean’s methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.
      • A session bean is not shared; it can have only one client.
      • The Session bean can be either stateless or stateful.
      Session Beans Copyright © Oded Nissan 2009
      • Does not maintain a conversational state with the client. Each method invocation is stateless.
      • Stateless session beans cannot have member variables.
      • The server maintains session beans in a pool, it can then assign the client different instances of the same bean over different invocations.
      Stateless Session Beans Copyright © Oded Nissan 2009
      • Maintain conversational state with the client using its instance variables.
      • Each instance is “pinned” to a specific client by the server.
      • If the client removes the bean or terminates, the session ends and the state disappears.
      Stateful Session Beans Copyright © Oded Nissan 2009
      • At any given time, only one client has access to the bean instance.
      • The state of the bean is not persistent, existing only for a short period (perhaps a few hours).
      • The bean implements a web service.
      When to use Session Beans ? Copyright © Oded Nissan 2009
      • The bean’s state represents the interaction between the bean and a specific client.
      • The bean needs to hold information about the client across method invocations.
      • The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
      • Behind the scenes, the bean manages the work flow of several enterprise beans.
      When to use Stateful Session Beans ? Copyright © Oded Nissan 2009
      • Stateless Session beans are considered more scalable since they don’t maintain state. Therefore they are more commonly used than Stateful session beans.
      • Many developers prefer to manage state on the Web tier, instead of using stateful session beans.
      • In general most of the EJBs developed are stateless session beans since they represent a generic business service.
      Session Beans Copyright © Oded Nissan 2009
      • A client can access a session bean only through the methods defined in the bean’s business interface. The business interface defines the client’s view of a bean. All other aspects of the bean (method implementations and deployment settings) are hidden from the client.
      • A client can access the EJB either locally or remotely.
      • The Client looks up the EJB in the JDNI directory tree and then invokes methods on the Bean.
      EJB Clients Copyright © Oded Nissan 2009
      • import javax.naming.InitialContext;
      • public class Client {
      • public static void main(String[] args) throws Exception
      • {
      • InitialContext ctx = new InitialContext(); Calculator calculator = (Calculator) ctx.lookup("CalculatorBean/remote"); System.out.println("1 + 1 = " + calculator.add(1, 1)); System.out.println("1 - 1 ="+calculator.subtract(1,1));
      • }
      • }
      EJB Client Example Copyright © Oded Nissan 2009
      • A remote client of an enterprise bean has the following traits:
        • It can run on a different machine and a different Java virtual machine (JVM) than the enterprise bean it accesses. (It is not required to run on a different JVM.)
        • It can be a web component, an application client, or another enterprise bean.
        • To a remote client, the location of the enterprise bean is transparent.
      Remote Clients Copyright © Oded Nissan 2009
      • To create an enterprise bean that allows remote access, you must do one of the following:
        • Decorate the business interface of the enterprise bean with the @Remote annotation:
          • @Remote public interface InterfaceName { ... }
        • Decorate the bean class with @Remote, specifying the business interface or interfaces:
          • @Remote(InterfaceName.class) public class BeanName implements InterfaceName { ... }
      Remote Client Copyright © Oded Nissan 2009
      • The remote Interface defines the business methods of the bean that can be accessed by remote clients:
      Remote Client Copyright © Oded Nissan 2009
      • A local client has these characteristics:
      • It must run in the same JVM as the enterprise bean it accesses.
      • It can be a web component or another enterprise bean.
      • To the local client, the location of the enterprise bean it accesses is not transparent.
      Local Clients Copyright © Oded Nissan 2009
      • The interface is by default a local interface. To define a local client:
        • Annotate the business interface of the enterprise bean as a @Local interface. For example:
          • @Local public interface InterfaceName { ... }
        • Specify the interface by decorating the bean class with @Local and specify the interface name. For example:
          • @Local(InterfaceName.class) public class BeanName implements InterfaceName { ... }
      Local Clients Copyright © Oded Nissan 2009
      • The Client type- If an enterprise bean is accessed by application clients, then it should allow remote access.
      • Performance – local access is faster, however distribution allows scalability.
      • Distribution – Should the components be distributed ?
      Choosing between remote and local clients. Copyright © Oded Nissan 2009
      • The business interface:
      • public interface Calculator{
      • int add(int x, int y);
      • int subtract(int x, int y);
      • }
      Stateless Session Bean Example Copyright © Oded Nissan 2009
      • The local Interface:
      • @Local public interface CalculatorLocal extends Calculator {
      • }
      • The remote Interface:
      • @Remote public interface CalculatorRemote extends Calculator
      • {
      • }
      Stateless Session Bean Example Copyright © Oded Nissan 2009
      • The bean implementation:
      • @Stateless public class CalculatorBean implements CalculatorRemote, CalculatorLocal
      • {
      • public int add(int x, int y)
      • {
      • return x + y;
      • }
      • public int subtract(int x, int y)
      • { return x - y; }
      • }
      Stateless Session Bean Example Copyright © Oded Nissan 2009
      • A Stateless Session Bean (SLS) is maintained in an object pool by the EJB container.
      • It can be in either of two states:
        • Does not exist
        • Method ready Pool
      The Stateless Session bean Life Cycle Copyright © Oded Nissan 2009
    • The Stateless Session bean Life Cycle Copyright © Oded Nissan 2009
      • No pooling. Each instance is “pinned” to a specific client.
      • Possible states:
        • Does not exist- before creation, after destroy.
        • Method ready
        • Passivated – the container passivates unused instances
      Stateful Session bean lifecycle Copyright © Oded Nissan 2009
    • Stateful Session bean lifecycle Copyright © Oded Nissan 2009
      • The Application server has a registry for storing JEE resources.
      • What can we store in the ENC ?
        • References to EJB interfaces, a JMS queue or topic destination, JMS connection factories, data sources, any JCA resource, and even primitive values.
      • The JNDI ENC can be accessed using the JNDI API
      The JNDI ENC (Enterprise naming context) Copyright © Oded Nissan 2009
      • @Stateful
      • @EJB(name="ejb/ProcessPayment", beanInterface=ProcessPaymentLocal.class, beanName="ProcessPaymentBean")
      • public class TravelAgentBean implements TravelAgentRemote
      • { ...
      • }
      Registering an EJB in the ENC Copyright © Oded Nissan 2009
      • Use the JDNI API, create an InitialContext and call the lookup method.
      • Use the EJBContext object and call the lookup method.
      • Use the EJB3 dependency injection feature.
      • By default the name of an EJB is in the form:
      • “ Java:comp/env/<package path>/<ejb class name>”
      Looking up an EJB in the ENC Copyright © Oded Nissan 2009
      • import javax.naming.InitialContext;
      • public class Client {
      • public static void main(String[] args) throws Exception
      • {
      • InitialContext ctx = new InitialContext(); Calculator calculator = (Calculator) ctx.lookup(&quot;CalculatorBean/remote&quot;); System.out.println(&quot;1 + 1 = &quot; + calculator.add(1, 1)); System.out.println(&quot;1 - 1 =&quot;+calculator.subtract(1,1));
      • }
      • }
      Client Using JNDI Copyright © Oded Nissan 2009
      • The javax.ejb.SessionContext interface provides a view into the EJB container's environment. The SessionContext object can be used as the bean instance's interface to the EJB container to obtain information about the context of the method invocation call and to provide quick access to various EJB services. A session bean can obtain a reference to its SessionContext by using the @Resource annotation:
      • @Stateless public class ProcessPaymentBean
      • implements ProcessPaymentLocal {
      • @Resource SessionContext ctx;
      Session Context Copyright © Oded Nissan 2009
      • SessionContext extends the javax.ejb.EJBContext class. EJBContext defines several methods that provide useful information to a bean at runtime.
      • Here are some useful methods in EJB Context, looking up resources:
        • public Object lookup(String name);
      EJBContext Copyright © Oded Nissan 2009
      • Security Methods:
        • public java.security.Principal getCallerPrincipal( ); public boolean isCallerInRole(String roleName);
      • Transaction Methods:
        • public javax.transaction.UserTransaction getUserTransaction( ) throws java.lang.IllegalStateException;
        • public boolean getRollbackOnly( ) throws java.lang.IllegalStateException;
        • public void setRollbackOnly( ) throws java.lang.IllegalStateException;
      EJBContext Copyright © Oded Nissan 2009
      • The EJBContext.getCallerPrincipal( ) method is used to obtain the java.security.Principal object representing the client that is currently accessing the bean. The Principal object can, for example, be used by an EJB to track the identities of clients making updates:
        • @Stateless public class BankBean implements Bank {
          • @Resource SessionContext context;
          • ... public void withdraw(int acctid, double amount) throws AccessDeniedException
          • {
          • String modifiedBy = principal.getName( );
          • ... }
          • ... }
      EJBContext Copyright © Oded Nissan 2009
      • The EJBContext.isCallerInRole( ) method tells you whether the client accessing the bean is a member of a specific role, identified by a role name. This method is useful when more access control is needed than simple method-based access control can provide:
          • @Stateless public class BankBean implements Bank {
          • @Resource SessionContext context;
          • public void withdraw(int acctid, double amount) throws AccessDeniedException
          • {
          • if (amount > 10000) {
          • boolean isManager = context.isCallerInRole(&quot;Manager&quot;);
          • if (!isManager) { // Only Managers can withdraw more than 10k. throw new AccessDeniedException( );
          • } }
      EJBContext Copyright © Oded Nissan 2009
    • Exercise Copyright © Oded Nissan 2009
    • Security Copyright © Oded Nissan 2009
      • In a secure EJB application, authentication involves verifying that a user is who she says she is. When a remote client logs on to the EJB system, it is associated with a security identity for the duration of that session. Once a remote client application has been associated with a security identity, it is ready to use beans to accomplish some task. When a client invokes a method on a bean, the EJB server implicitly passes the client's identity with the method invocation. When the EJB object receives the method invocation, it checks the identity to ensure that the client is valid and is allowed to invoke that method.
      Security Copyright © Oded Nissan 2009
      • When invoking on a remote EJB, many application servers accomplish authentication by using the JNDI API. For example, a client using JNDI can provide authenticating information using the JNDI API to access a server or resource in the server. This information is frequently passed when the client attempts to initiate a JNDI connection on the EJB server.
      Security- Authentication Copyright © Oded Nissan 2009
      • The following code shows how a client's password and username can be added to the connection properties for obtaining a JNDI connection to the EJB server:
        • properties.put(Context.SECURITY_PRINCIPAL, userName);
        • properties.put(Context.SECURITY_CREDENTIALS, userPassword);
        • InitialContext ctx = new InitialContext(properties);
        • alculator calculator = (Calculator) ctx.lookup(&quot;Calculator&quot;);
      Using JNDI to login to the server Copyright © Oded Nissan 2009
      • Although JNDI is a common way for most application servers to perform authentication, sometimes users need a better abstraction for obtaining security information.
      • Many application servers provide a mechanism other than JNDI with which to authenticate. For instance, the JBoss application server uses the JAAS specification, which provides a rich API for performing authentication.
      Security- Authentication Copyright © Oded Nissan 2009
      • Once a user is authenticated by a vendor-specific mechanism, he must be checked to see if he is allowed to invoke a particular EJB method. Authorization is performed in Java EE and EJB by associating one or more roles with a given user and then assigning method permissions based on that role
      • The roles used to describe authorization are considered logical roles because they do not directly reflect users, groups, or any other security identities in a specific operational environment. EJB security roles are mapped to real-world user groups and users when the bean is deployed. This mapping allows a bean to be portable
      Security - Authorization Copyright © Oded Nissan 2009
      • When applied to the bean class the @RolesAllowed annotation specifies the default set of roles that are permitted to access the bean.
      • When applied to a bean method it specifies the default set of roles that are permitted to access the method.
      • The @PermitAll annotation specifies that any authenticated user is permitted to invoke the method/class.
      Security - Authorization Copyright © Oded Nissan 2009
        • @Stateless @RolesAllowed(&quot;AUTHORIZED_TRAVEL_AGENT&quot;)
        • public class ProcessPaymentBean implements ProcessPaymentRemote, ProcessPaymentLocal
        • {
        • ...
        • @PermitAll public boolean byCash(Customer customer, double amount) throws PaymentException
        • {
        • ...
        • }
        • @RolesAllowed(&quot;CHECK_FRAUD_ENABLED&quot;) public boolean byCheck(Customer customer, CheckDO check, double amount) throws PaymentException
        • {
        • ... }
      Security – Authorization Example Copyright © Oded Nissan 2009
      • The @RunAs role can also be specified to the bean class.
      • The runAs role is used as the enterprise bean's identity when it tries to invoke methods on other beans and this identity isn't necessarily the same as the identity that's currently accessing the bean.
      Security - Authorization Copyright © Oded Nissan 2009
      • We can use the getCallerInRole() and getCallerPrincipal() from EJBContext to perform our own programmatic security checks.
          • @Stateless public class BankBean implements Bank {
          • @Resource SessionContext context;
          • public void withdraw(int acctid, double amount) throws AccessDeniedException
          • {
          • if (amount > 10000) {
          • boolean isManager = context.isCallerInRole(&quot;Manager&quot;);
          • if (!isManager) { // Only Managers can withdraw more than 10k. throw new AccessDeniedException( );
          • } }
      Security - Programmatic Copyright © Oded Nissan 2009
    • Dependency Injection Copyright © Oded Nissan 2009
      • The process of supplying an external dependency to a software component.
      • A form of inversion of control, where the dependency is “given” to the software component, rather than the component obtaining it.
      • Sometimes called the “Holywood Pattern” (don’t call us we will call you).
      What is Dependency Injection ? Copyright © Oded Nissan 2009
      • Dependency injection is the inverse of JNDI. It lets you declare dependencies and lets the Java EE container handle the complexities of service or resource instantiation and initialization when the resource is required.
      • Based on the declaration of resources using annotations or deployment descriptors, the Java EE 5.0 container injects an instance of the resource when it's required.
      Dependency Injection Copyright © Oded Nissan 2009
    • Dependency Injection Copyright © Oded Nissan 2009
      • Dependency injection can only be used by managed classes--those that are managed by Java EE containers such as EJB or servlets--rather than by all classes such as helper classes.
      • For example, if we have an EJB, we can use dependency injection on an EJB 3.0 bean class, but not on a helper class upon which the EJB depends. Java EE 5.0 defines dependency injection of resources and EJB, web services in EJB, web and application client modules.
      Dependency Injection Copyright © Oded Nissan 2009
      • Field Injection – inject a resource into a field.
      • To use a field injection, simply define a field and annotate it to be a resource reference. If you don't define the resource's name and type, the container will derive this information from the field's name and type. For example, you can inject a DataSource to a field as follows:
        • @Resource private javax.sql.DataSource AdventureDB;
      Field Injection Copyright © Oded Nissan 2009
      • Method Injection – inject a resource using a setter method.
        • @Resource
        • private void setAdventureDB(javax.sql.DataSource ds)
        • {
        • adventureDB = ds;
        • }
        • private DataSource adventureDB;
      Method Injection Copyright © Oded Nissan 2009
      • References to other EJBs can also be injected.
      • Inject an EJB by using the @EJB annotation:
          • @EJB private Calculator calculator;
          • Or using method injection:
          • @EJB(beanName=&quot;CalculatorBean&quot;)
          • public void setCalculator(Calculator c)
          • {
          • set = c;
          • }
      EJB Injection Copyright © Oded Nissan 2009
      • The specification isn't very detailed in terms of exactly how the EJB container should resolve this reference.
      • JBOSS specifically, tries to identify which bean uses the annotated class, if the “beanName” attribute is specified, it searches for a bean with that name, if the “mappedTo” attribute is specified it searches the JNDI ENC.
      EJB Injection Copyright © Oded Nissan 2009
    • Message Driven Beans Copyright © Oded Nissan 2009
      • JMS is a vendor-neutral API that can be used to access enterprise messaging systems
      • Applications that use JMS are called JMS clients , and the messaging system that handles routing and delivery of messages is called the JMS provider.
      • A JMS client that sends a message is called a producer , and a JMS client that receives a message is called a consumer . A single JMS client can be both a producer and a consumer.
      Introduction to JMS Copyright © Oded Nissan 2009
      • A JMS application is composed of the following parts:
      • A JMS provider: A messaging system that implements the JMS specification.
      • JMS clients: Java applications that send and receive messages.
      • Messages: Objects that are used to communicate information between JMS clients.
      • Administered objects: Preconfigured JMS objects that are created by an administrator for the use of JMS clients.
      JMS Architecture Copyright © Oded Nissan 2009
      • JMS supports two different message delivery models:
      • Point-to-Point (Queue destination): In this model, a message is delivered from a producer to one consumer.
      • Publish/Subscribe (Topic destination): In this model, a message is delivered from a producer to any number of consumers.
      JMS Delivery Modes Copyright © Oded Nissan 2009
      • The messages are delivered to the destination, which is a queue, and then delivered to one of the consumers registered for the queue. While any number of producers can send messages to the queue, each message is guaranteed to be delivered, and consumed by one consumer. If no consumers are registered to consume the messages, the queue holds them until a consumer registers to consume them.
      Point to Point Copyright © Oded Nissan 2009
      • Messages are delivered to the topic destination, and then to all active consumers who have subscribed to the topic. In addition, any number of producers can send messages to a topic destination, and each message can be delivered to any number of subscribers. If there are no consumers registered, the topic destination doesn't hold messages unless it has durable subscription for inactive consumers. A durable subscription represents a consumer registered with the topic destination that can be inactive at the time the messages are sent to the topic.
      Publish/Subscribe Copyright © Oded Nissan 2009
      • A JMS application consists of a set of application-defined messages and a set of clients that exchange them.
      • JMS clients interact by sending and receiving messages using the JMS API.
      • A message is composed of three parts: header , properties , and a body .
      The JMS programming Model Copyright © Oded Nissan 2009
      • The JMS specification defined six type or classes of messages that a JMS provider must support:
        • Message : This represents a message without a message body.
        • StreamMessage : A message whose body contains a stream of Java primitive types. It is written and read sequentially.
        • MapMessage : A message whose body contains a set of name/value pairs. The order of entries is not defined.
        • TextMessage : A message whose body contains a Java string...such as an XML message.
        • ObjectMessage : A message whose body contains a serialized Java object.
        • BytesMessage : A message whose body contains a stream of uninterpreted bytes.
      JMS Message Types Copyright © Oded Nissan 2009
    • Producing and Consuming Messages Copyright © Oded Nissan 2009
      • Creating a connection:
      • QueueConnection conn;
      • QueueSession session;
      • Queue que;
      • InitialContext iniCtx = new InitialContext();
      • Object tmp = iniCtx.lookup(&quot;ConnectionFactory&quot;);
      • QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
      • conn = qcf.createQueueConnection();
      • que = (Queue) iniCtx.lookup(&quot;queue/testQueue&quot;);
      • session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); conn.start();
      Sample Code Copyright © Oded Nissan 2009
      • Sending a message:
      • // Send a text msg
      • QueueSender send = session.createSender(que);
      • TextMessage tm = session.createTextMessage(text);
      • send.send(tm);
      • Receiving a message:
      • // Set the async listener
      • QueueReceiver recv = session.createReceiver(que);
      • recv.setMessageListener(new ExListener());
      • public static class ExListener implements MessageListener {
      • public void onMessage(Message msg) {
      • TextMessage tm = (TextMessage) msg;
      • try {
      • log.info(&quot;onMessage, recv text=&quot; + tm.getText());
      • }
      • catch(Throwable t) {
      • … .
      Sample Code Copyright © Oded Nissan 2009
      • Message-driven beans (MDBs) are stateless, server-side, transaction-aware components for processing asynchronous messages delivered via JMS. While a message-driven bean is responsible for processing messages, its container manages the component's environment, including transactions, security, resources, concurrency, and message acknowledgment..
      • An MDB can process hundreds of JMS messages concurrently because numerous instances of the MDB can execute concurrently in the container.
      Message Driven Beans Copyright © Oded Nissan 2009
      • @MessageDriven
      • (activationConfig = { @ActivationConfigProperty(propertyName=&quot;destinationType&quot;, propertyValue=&quot;javax.jms.Queue&quot;), @ActivationConfigProperty(propertyName=&quot;destination&quot;, propertyValue=&quot;queue/tutorial/example&quot;) })
      • public class ExampleMDB implements MessageListener
      • {
      • public void onMessage(Message recvMsg)
      • {
      • System.out.println(&quot;----------------&quot;);
      • System.out.println(&quot;Received message&quot;);
      • }
      • }
      MDB Example Copyright © Oded Nissan 2009
    • Message Driven Beans Copyright © Oded Nissan 2009
      • An MDB can be in two states:
      • Does not exist
      • Method Ready Pool – the pool is maintained by the container, when the container decides to reduce the number of MDB instances it may destroy some instances.
      The MDB Life Cycle Copyright © Oded Nissan 2009
    • The MDB Life Cycle Copyright © Oded Nissan 2009
      • MDB clients are regular JMS clients, in contrast to other EJB types.
      • Use MDBs to perform asynchronous operations.
      • MDBs can be a good fit for handling a high load of events or observations.
      Message Driven Beans Copyright © Oded Nissan 2009
    • Transactions Copyright © Oded Nissan 2009
      • Atomic – must execute completely or not at all.
      • Consistent – Must result in consistent data.
      • Isolated - must be allowed to execute without interference from other processes or transactions.
      • Durable - all the data changes made during the course of a transaction must be written to some type of physical storage before the transaction is successfully completed.
      The ACID Transaction Attributes: Copyright © Oded Nissan 2009
      • With declarative transaction management, the transactional behavior of EJBs is managed by the container.
      • Declarative transaction management reduces the complexity of transactions for EJB developers and application developers and makes it easier to create robust transactional applications.
      Declarative Transaction Management Copyright © Oded Nissan 2009
      • NotSupported
      • Supports
      • Required
      • RequiresNew
      • Mandatory
      • Never
      Transaction Attributes Copyright © Oded Nissan 2009
        • Invoking a method on an EJB with this transaction attribute suspends the transaction until the method is completed.
      Not Supported Copyright © Oded Nissan 2009
        • The bean method will be included in the transaction scope if it is invoked within a transaction.
      Supports Copyright © Oded Nissan 2009
        • The bean method must be invoked within the scope of a transaction. The container will create a new transaction if one is not present.
      Required Copyright © Oded Nissan 2009
      • A new transaction will be started, even if the bean is invoked within an existing transaction scope.
      Requires New Copyright © Oded Nissan 2009
      • The bean must be invoked within a transaction scope. An exception will be thrown if there is no transaction.
      Mandatory Copyright © Oded Nissan 2009
      • The EJB must not be invoked within a transaction. If it is, an exception is thrown.
      Never Copyright © Oded Nissan 2009
      • @Stateless
      • @TransactionAttribute(NOT_SUPPORTED)
      • public class TravelAgentBean implements TravelAgentRemote
      • {
      • public void setCustomer(Customer cust) {
      • ...
      • }
      • @TransactionAttribute(REQUIRED)
      • public TicketDO bookPassage(CreditCardDO card, double price)
      • { ...
      • }
      • }
      Specifying Transactions Copyright © Oded Nissan 2009
      • Use JTA for explicit transaction management. For example:
      • UserTransaction ut = ejbContext.getUserTransaction( );
      • ut.begin( );
      • // Do some work.
      • ut.commit( );
      Explicit Transaction Management Copyright © Oded Nissan 2009
      • System exceptions represent unknown internal errors. The EJB container throws system exceptions when it encounters an internal failure.
      • Application exceptions are thrown by the application in response to a business logic error.
      Transactions and Exceptions Copyright © Oded Nissan 2009
      • A system exception will be handled automatically by the container. The container will perform the following actions:
        • Roll back the transaction
        • Log the error
        • Discard the EJB instance.
      System Exceptions Copyright © Oded Nissan 2009
      • Application exceptions are always delivered directly to the client without being repackaged as an EJBException type. By default, they do not cause a transaction to roll back. In this case, the client has an opportunity to recover after an application exception is thrown.
      • The @javax.ejb.ApplicationException annotation may be used to force an application exception to roll back the transaction automatically. Another option is to call EJBContext.setRollBackOnly().
      Application Exceptions Copyright © Oded Nissan 2009
      • In case of a system exception the client will receive RemoteException or EJBException in case of Container managed transaction (CMT) and a EJBTransactionRolledbackException in case of Client initiated transaction.
      • In case of an application exception the client will receive the application exception thrown.
      Transactions and Exceptions Copyright © Oded Nissan 2009
      • A transaction rollback in an MDB will result in the consumed message being put back into the queue.
      Transactions and Exceptions Copyright © Oded Nissan 2009
      • A SFS bean might also want to restore itself to a consistent state in case of a transaction rollback. It can do so by implementing the SessionSynchronization interface:
        • public interface javax.ejb.SessionSynchronization {
          • public abstract void afterBegin( ) throws RemoteException;
          • public abstract void beforeCompletion( ) throws RemoteException;
          • public abstract void afterCompletion(boolean committed) throws RemoteException;
        • }
      Stateful Session Beans and Transactions. Copyright © Oded Nissan 2009
    • Stateful Session Beans and Transactions. Copyright © Oded Nissan 2009
      • Transactions handle the ACID properties, but what about concurrency ?
      • Transaction isolation deals with the conflicts created when two or more transactions work on the same data.
      • It is defined in terms of isolation conditions called dirty reads, repeatable reads and phantom reads.
      Transaction Isolation Copyright © Oded Nissan 2009
      • Occurs when a transaction reads uncommitted changes made by a previous transaction. If the first transaction is rolled back, the data read by the second transaction becomes invalid because the rollback undoes the changes. The second transaction will not be aware that the data it has read has become invalid
      Dirty Read Copyright © Oded Nissan 2009
      • Occurs when the same data is read twice during the same transaction. We must ensure that the two calls will return the same data even if another transaction changed it.
      Repeatable Read Copyright © Oded Nissan 2009
      • Occurs when the same data is read twice during the same transaction. But this time a record is inserted or deleted by another transaction between reads.
      Phantom Reads Copyright © Oded Nissan 2009
      • Read Uncommitted - The transaction can read uncommitted data Dirty reads, nonrepeatable reads, and phantom reads can occur.
      • Read Committed - The transaction cannot read uncommitted data; data that is being changed by a different transaction cannot be read. Dirty reads are prevented; nonrepeatable reads and phantom reads can occur.
      • Repeatable Read - The transaction cannot change data that is being read by a different transaction. Dirty reads and nonrepeatable reads are prevented; phantom reads can occur.
      • Serializable - The transaction has exclusive read and update privileges; different transactions can neither read nor write to the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. This isolation level is the most restrictive.
      Transaction Isolation Levels Copyright © Oded Nissan 2009
      • Isolation levels can be set in JEE in two ways:
        • At the Database level using the JDBC datasource properties.
        • Using the EntityManager of JPA Entities, that we will discuss later.
      Setting Isolation Levels Copyright © Oded Nissan 2009
      • We need to handle transaction collisions consistently. If two transactions run concurrently on the same data, we want do either detect the collision or prevent it.
      • Optimistic Locking – Detects the collision.
      • Pessimistic Locking – Avoids the collision.
      Database Locking Strategies Copyright © Oded Nissan 2009
      • An XA transaction is a global transaction that may span multiple resources.
      • An XA transaction involves a coordinating transaction manager, with one or more databases (or other resources, like JMS) all involved in a single global transaction.
      • XA transactions come from the X/Open group specification on distributed, global transactions. JTA includes the X/Open XA spec, in modified form.
      XA Transactions Copyright © Oded Nissan 2009
      • The Transaction Manager coordinates all of this through a protocol called Two Phase Commit (2PC). This protocol also has to be supported by the individual resources.
      • An XA datasource is a data source that can participate in an XA global transaction. A non-XA datasource generally can't participate in a global transaction.
      • In JEE JTA supports XA transaction, we define an XA datasource to support XA.
      XA Transactions Copyright © Oded Nissan 2009
      • In order to synchronize the different resources participating in the transaction the protocol commits in two phases:
        • First it asks all resources if they can perform a commit.
        • If they can a commit if performed on all resources.
        • Otherwise the transaction is rolled back on all resources.
      The Two Phase Commit Protocol Copyright © Oded Nissan 2009
    • The Two Phase Commit Protocol Copyright © Oded Nissan 2009
    • EJB Design Patterns Copyright © Oded Nissan 2009
      • A general solution to a problem in software design.
      • A design template that should be applied to the specific context.
      • Design patterns are documented, classified and named.
      What are Design Patterns ? Copyright © Oded Nissan 2009
      • Produce a clean, maintainable and efficient solution.
      • Use the optimal known solution (don’t reinvent the wheel).
      • A way to communicate the design solution.
      Why do we need design patterns ? Copyright © Oded Nissan 2009
      • EJB Design Patterns were first defined in a book by Floyd Marinescu in 2002. Back then EJB 2.1 was the standard.
      • Since the evolution of EJB to the EJB 3.0 spec some of the patterns became irrelevant.
      • Examples of irrelevant patterns:
        • The Service Locator – injection is used in EJB 3.0
        • Dual Persistent Entity Bean – no Entity Beans in EJB 3.0
        • Versioning and locking – addressed in JPA.
      Overview Copyright © Oded Nissan 2009
      • We will discuss some of the relevant patterns as described in Sun’s JEE Pattern catalog and Floyd’s EJB Design Patterns book.
      • Suns JEE Patterns - http://72.5.124.55/developer/technicalArticles/J2EE/patterns/
      • EJB Design Pattern Book by Floyd Marinescu - http://c2.com/cgi/wiki?EjbDesignPatternsBook
      Overview Copyright © Oded Nissan 2009
      • The Session Façade
      • The Message Façade
      • Transfer Object
      • EJB Command
      EJB Design Patterns Copyright © Oded Nissan 2009
      • The Session façade pattern defines a higher-level business component that contains and centralizes complex interactions between lower-level business components. A Session Facade is implemented as a session enterprise bean. It provides clients with a single interface for the functionality of an application or application subset. It also decouples lower-level business components from one another, making designs more flexible and comprehensible.
      • Related to the GOF Façade pattern.
      Session Facade Copyright © Oded Nissan 2009
    • Session Facade Copyright © Oded Nissan 2009
      • Low coupling – we can change the façade components without changing the façade interface.
      • Improve reusability – we can reuse EJBs that perform part of the use case in more than one Session façade.
      • Maintainability – cleaner separation between application logic and infrastructure code.
      Session Façade Advantages Copyright © Oded Nissan 2009
      • The Message Façade is useful when a use case requires invoking multiple EJBs in an asynchronous manner.
      • The Message façade is similar to the Session Façade but the façade is implemented as an MDB instead of a session bean.
      • Features the advantages and disadvantages of using a JMS messaging.
      Message Facade Copyright © Oded Nissan 2009
      • Group attributes together in a value object to reduce remote network calls.
      • Using the Transfer object reduces network traffic and improves performance.
      • A Transfer object fits well with a Session façade.
      Transfer Object Copyright © Oded Nissan 2009
      • Based on the GOF Command pattern.
      • Uses the command pattern to decouple the client from EJB. The client executes commands using a command pattern framework, all commands are piped through one EJB.
      EJB Command Copyright © Oded Nissan 2009
    • The GOF Command Pattern Copyright © Oded Nissan 2009
    • EJB Command Copyright © Oded Nissan 2009
    • Java Persistence API Overview Copyright © Oded Nissan 2009
      • ORM stands for Object Relational Mapping. The mapping of an object model into a relational database.
      • Popular ORM frameworks are Hibernate and Toplink.
      • ORM must deal with mapping a complex object model into a relational database.
      What is ORM ? Copyright © Oded Nissan 2009
      • Up to the 2.1 spec EJB Entity Beans were the ORM solution in J2EE
      • However, entity beans were very &quot;heavyweight&quot; and dependent on the application server and the entire Java EE runtime environment.
      • Lightweight open source ORM frameworks such as Hibernate gained popularity.
      EJB 2.1 Entity Beans Copyright © Oded Nissan 2009
      • In EJB 3.0 Entity Beans were removed from the spec and reinvented as “entities” and part of the JPA spec.
      • The JPA is considered a part of JEE 5 and EJB 3, but is also a standalone framework that can be used outside of a JEE container.
      • JPA is a lightweight ORM framework that resembles Hibernate.
      JPA and EJB 3.0 Copyright © Oded Nissan 2009
      • Entities are Plain Java Objects (POJOs).
      • Use of annotations to perform mapping.
      • Use of EJB-QL query language to perform queries.
      • JPA can run outside a JEE container.
      • Integrates with JEE transactions and dependency injection.
      • Configuration by exception – minimal configuration is required. Use configuration features only when you need to override the defaults.
      JPA Features Copyright © Oded Nissan 2009
      • The class must be annotated with the javax.persistence.Entity annotation.
      • The class must have a public or protected, no-argument constructor. The class may have other constructors.
      • The class must not be declared final. No methods or persistent instance variables must be declared final.
      • If an entity instance be passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface.
      • Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.
      • Persistent instance variables must be declared private, protected, or package-private, and can only be accessed directly by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.
      Requirements for Entity Classes Copyright © Oded Nissan 2009
      • A persistence unit defines the scope of entity persistence.
      • META-INF/persistence.xml defines the persistence units including:
        • Persistence provider
        • Data source to use
        • OR mapping information
        • Location of entity classes
      Persistence Unit Copyright © Oded Nissan 2009
      • The persistence context is the set of entities participating in a single unit of work.
      • These entities are managed by the entity manager.
      Persistence Context Copyright © Oded Nissan 2009
      • The Entity Manager stores and loads entities from persistence context.
      • The Entity Manager API allows an application to find,delete, update and add entities. (All CRUD operations).
      • Container managed Entity Managers
        • Obtained through JNDI lookup or injection.
        • Used in JEE environement.
      • Application managed Entity Managers
        • Obtained from an EntityManagerFactory
        • Used in JavaSE environments.
      Entity Manager Copyright © Oded Nissan 2009
      • Java Persistence Query Language (JPQL) is an extension of EJB Query Language (EJB-QL)
      • New Features:
        • Bulk update and delete
        • Join functions
        • Group by and having functions
        • Dynamic queries and named parameters.
      JPQL Copyright © Oded Nissan 2009
      • Examine the JPA examples
      JPA Examples Copyright © Oded Nissan 2009
      • What did we discuss ?
        • Overview
        • Session Beans
        • Security
        • Dependency Injection
        • Message Driven Beans (MDB)
        • Transactions
        • EJB Design Patterns
        • Java Persistence API (JPA) Overview
      Summary Copyright © Oded Nissan 2009