JEE Course - EJB

133
Enterprise Java Beans Copyright © Oded Nissan 2009

description

The

Transcript of JEE Course - EJB

Page 1: JEE Course - EJB

Enterprise Java Beans

Copyright © Oded Nissan 2009

Page 2: JEE Course - EJB

Overview Session Beans Security Dependency Injection Message Driven Beans (MDB) Transactions EJB Design Patterns Java Persistence API (JPA) Overview Summary

Copyright © Oded Nissan 2009

Enterprise Java Beans

Page 3: JEE Course - EJB

Overview

Copyright © Oded Nissan 2009

Page 4: JEE Course - EJB

Copyright © Oded Nissan 2009

The JEE Platform

Page 5: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

What is an EJB?

Page 6: JEE Course - EJB

Distributed components Transaction management support Security Scalability and fail-over Asynchronous Persistence – object relational mapping.

Copyright © Oded Nissan 2009

EJB Features

Page 7: JEE Course - EJB

● 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

Copyright © Oded Nissan 2009

EJB Advantages

Page 8: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

When to use EJB?

Page 9: JEE Course - EJB

Stateless Session Beans Stateful Session Beans Message Driven Beans – Asynchronous. Entities – Persistent. (part of the JPA spec).

Copyright © Oded Nissan 2009

EJB Types

Page 10: JEE Course - EJB

Session Beans

Copyright © Oded Nissan 2009

Page 11: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Session Beans

Page 12: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Stateless Session Beans

Page 13: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Stateful Session Beans

Page 14: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

When to use Session Beans?

Page 15: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

When to use Stateful Session Beans?

Page 16: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Session Beans

Page 17: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

EJB Clients

Page 18: JEE Course - EJB

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));

}}

Copyright © Oded Nissan 2009

EJB Client Example

Page 19: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Remote Clients

Page 20: JEE Course - EJB

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 { ... }

Copyright © Oded Nissan 2009

Remote Client

Page 21: JEE Course - EJB

The remote Interface defines the business methods of the bean that can be accessed by remote clients:

Copyright © Oded Nissan 2009

Remote Client

Page 22: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Local Clients

Page 23: JEE Course - EJB

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 { ... }

Copyright © Oded Nissan 2009

Local Clients

Page 24: JEE Course - EJB

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 ?

Copyright © Oded Nissan 2009

Choosing between remote and local clients.

Page 25: JEE Course - EJB

The business interface:

public interface Calculator{ int add(int x, int y); int subtract(int x, int y);}

Copyright © Oded Nissan 2009

Stateless Session Bean Example

Page 26: JEE Course - EJB

The local Interface: @Local public interface CalculatorLocal extends

Calculator { } The remote Interface: @Remote public interface CalculatorRemote

extends Calculator{ }

Copyright © Oded Nissan 2009

Stateless Session Bean Example

Page 27: JEE Course - EJB

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; }}

Copyright © Oded Nissan 2009

Stateless Session Bean Example

Page 28: JEE Course - EJB

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

Copyright © Oded Nissan 2009

The Stateless Session bean Life Cycle

Page 29: JEE Course - EJB

Copyright © Oded Nissan 2009

The Stateless Session bean Life Cycle

Page 30: JEE Course - EJB

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

Copyright © Oded Nissan 2009

Stateful Session bean lifecycle

Page 31: JEE Course - EJB

Copyright © Oded Nissan 2009

Stateful Session bean lifecycle

Page 32: JEE Course - EJB

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

Copyright © Oded Nissan 2009

The JNDI ENC (Enterprise naming context)

Page 33: JEE Course - EJB

@Stateful @EJB(name="ejb/ProcessPayment",

beanInterface=ProcessPaymentLocal.class, beanName="ProcessPaymentBean")

public class TravelAgentBean implements TravelAgentRemote

{ ... }

Copyright © Oded Nissan 2009

Registering an EJB in the ENC

Page 34: JEE Course - EJB

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>”

Copyright © Oded Nissan 2009

Looking up an EJB in the ENC

Page 35: JEE Course - EJB

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));

}}

Copyright © Oded Nissan 2009

Client Using JNDI

Page 36: JEE Course - EJB

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;

Copyright © Oded Nissan 2009

Session Context

Page 37: JEE Course - EJB

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);

Copyright © Oded Nissan 2009

EJBContext

Page 38: JEE Course - EJB

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;

Copyright © Oded Nissan 2009

EJBContext

Page 39: JEE Course - EJB

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( ); ... } ... }

Copyright © Oded Nissan 2009

EJBContext

Page 40: JEE Course - EJB

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("Manager"); if (!isManager) { // Only Managers can withdraw more than 10k. throw

new AccessDeniedException( ); } }

Copyright © Oded Nissan 2009

EJBContext

Page 41: JEE Course - EJB

Exercise

Copyright © Oded Nissan 2009

Page 42: JEE Course - EJB

Security

Copyright © Oded Nissan 2009

Page 43: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Security

Page 44: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Security- Authentication

Page 45: JEE Course - EJB

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("Calculator");

Copyright © Oded Nissan 2009

Using JNDI to login to the server

Page 46: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Security- Authentication

Page 47: JEE Course - EJB

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

Copyright © Oded Nissan 2009

Security - Authorization

Page 48: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Security - Authorization

Page 49: JEE Course - EJB

@Stateless @RolesAllowed("AUTHORIZED_TRAVEL_AGENT") public class ProcessPaymentBean implements

ProcessPaymentRemote, ProcessPaymentLocal { ... @PermitAll public boolean byCash(Customer customer, double

amount) throws PaymentException { ... } @RolesAllowed("CHECK_FRAUD_ENABLED") public boolean

byCheck(Customer customer, CheckDO check, double amount) throws PaymentException

{ ... }

Copyright © Oded Nissan 2009

Security – Authorization Example

Page 50: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Security - Authorization

Page 51: JEE Course - EJB

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("Manager"); if (!isManager) { // Only Managers can withdraw more than 10k. throw new

AccessDeniedException( ); } }

Copyright © Oded Nissan 2009

Security - Programmatic

Page 52: JEE Course - EJB

Dependency Injection

Copyright © Oded Nissan 2009

Page 53: JEE Course - EJB

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).

Copyright © Oded Nissan 2009

What is Dependency Injection ?

Page 54: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Dependency Injection

Page 55: JEE Course - EJB

Copyright © Oded Nissan 2009

Dependency Injection

Page 56: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Dependency Injection

Page 57: JEE Course - EJB

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;

Copyright © Oded Nissan 2009

Field Injection

Page 58: JEE Course - EJB

Method Injection – inject a resource using a setter method.@Resource private void setAdventureDB(javax.sql.DataSource

ds){ adventureDB = ds; } private DataSource adventureDB;

Copyright © Oded Nissan 2009

Method Injection

Page 59: JEE Course - EJB

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="CalculatorBean") public void setCalculator(Calculator c) { set = c; }

Copyright © Oded Nissan 2009

EJB Injection

Page 60: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

EJB Injection

Page 61: JEE Course - EJB

Message Driven Beans

Copyright © Oded Nissan 2009

Page 62: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Introduction to JMS

Page 63: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

JMS Architecture

Page 64: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

JMS Delivery Modes

Page 65: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Point to Point

Page 66: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Publish/Subscribe

Page 67: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

The JMS programming Model

Page 68: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

JMS Message Types

Page 69: JEE Course - EJB

Copyright © Oded Nissan 2009

Producing and Consuming Messages

Page 70: JEE Course - EJB

Creating a connection:

QueueConnection conn; QueueSession session; Queue que;

InitialContext iniCtx = new InitialContext(); Object tmp = iniCtx.lookup("ConnectionFactory"); QueueConnectionFactory qcf = (QueueConnectionFactory) tmp; conn = qcf.createQueueConnection(); que = (Queue) iniCtx.lookup("queue/testQueue"); session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); conn.start();

Copyright © Oded Nissan 2009

Sample Code

Page 71: JEE Course - EJB

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("onMessage, recv text=" + tm.getText()); } catch(Throwable t) {

….

Copyright © Oded Nissan 2009

Sample Code

Page 72: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Message Driven Beans

Page 73: JEE Course - EJB

@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName="destinationType",

propertyValue="javax.jms.Queue"), @ActivationConfigProperty(propertyName="destination",

propertyValue="queue/tutorial/example") })

public class ExampleMDB implements MessageListener{

public void onMessage(Message recvMsg) { System.out.println("----------------"); System.out.println("Received message");

}}

Copyright © Oded Nissan 2009

MDB Example

Page 74: JEE Course - EJB

Copyright © Oded Nissan 2009

Message Driven Beans

Page 75: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

The MDB Life Cycle

Page 76: JEE Course - EJB

Copyright © Oded Nissan 2009

The MDB Life Cycle

Page 77: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Message Driven Beans

Page 78: JEE Course - EJB

Transactions

Copyright © Oded Nissan 2009

Page 79: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

The ACID Transaction Attributes:

Page 80: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Declarative Transaction Management

Page 81: JEE Course - EJB

NotSupported Supports Required RequiresNew Mandatory Never

Copyright © Oded Nissan 2009

Transaction Attributes

Page 82: JEE Course - EJB

• Invoking a method on an EJB with this transaction attribute suspends the transaction until the method is completed.

Copyright © Oded Nissan 2009

Not Supported

Page 83: JEE Course - EJB

• The bean method will be included in the transaction scope if it is invoked within a transaction.

Copyright © Oded Nissan 2009

Supports

Page 84: JEE Course - EJB

• The bean method must be invoked within the scope of a transaction. The container will create a new transaction if one is not present.

Copyright © Oded Nissan 2009

Required

Page 85: JEE Course - EJB

A new transaction will be started, even if the bean is invoked within an existing transaction scope.

Copyright © Oded Nissan 2009

Requires New

Page 86: JEE Course - EJB

The bean must be invoked within a transaction scope. An exception will be thrown if there is no transaction.

Copyright © Oded Nissan 2009

Mandatory

Page 87: JEE Course - EJB

The EJB must not be invoked within a transaction. If it is, an exception is thrown.

Copyright © Oded Nissan 2009

Never

Page 88: JEE Course - EJB

@Stateless @TransactionAttribute(NOT_SUPPORTED) public class TravelAgentBean implements TravelAgentRemote {

public void setCustomer(Customer cust) {...} @TransactionAttribute(REQUIRED) public TicketDO bookPassage(CreditCardDO card, double

price) { ... }

}

Copyright © Oded Nissan 2009

Specifying Transactions

Page 89: JEE Course - EJB

Use JTA for explicit transaction management. For example:

UserTransaction ut = ejbContext.getUserTransaction( ); ut.begin( ); // Do some work. ut.commit( );

Copyright © Oded Nissan 2009

Explicit Transaction Management

Page 90: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Transactions and Exceptions

Page 91: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

System Exceptions

Page 92: JEE Course - EJB

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().

Copyright © Oded Nissan 2009

Application Exceptions

Page 93: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Transactions and Exceptions

Page 94: JEE Course - EJB

A transaction rollback in an MDB will result in the consumed message being put back into the queue.

Copyright © Oded Nissan 2009

Transactions and Exceptions

Page 95: JEE Course - EJB

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; }

Copyright © Oded Nissan 2009

Stateful Session Beans and Transactions.

Page 96: JEE Course - EJB

Copyright © Oded Nissan 2009

Stateful Session Beans and Transactions.

Page 97: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Transaction Isolation

Page 98: JEE Course - EJB

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

Copyright © Oded Nissan 2009

Dirty Read

Page 99: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Repeatable Read

Page 100: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Phantom Reads

Page 101: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Transaction Isolation Levels

Page 102: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Setting Isolation Levels

Page 103: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Database Locking Strategies

Page 104: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

XA Transactions

Page 105: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

XA Transactions

Page 106: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

The Two Phase Commit Protocol

Page 107: JEE Course - EJB

Copyright © Oded Nissan 2009

The Two Phase Commit Protocol

Page 108: JEE Course - EJB

EJB Design Patterns

Copyright © Oded Nissan 2009

Page 109: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

What are Design Patterns ?

Page 110: JEE Course - EJB

Produce a clean, maintainable and efficient solution.

Use the optimal known solution (don’t reinvent the wheel).

A way to communicate the design solution.

Copyright © Oded Nissan 2009

Why do we need design patterns ?

Page 111: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Overview

Page 112: JEE Course - EJB

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

Copyright © Oded Nissan 2009

Overview

Page 113: JEE Course - EJB

The Session Façade The Message Façade Transfer Object EJB Command

Copyright © Oded Nissan 2009

EJB Design Patterns

Page 114: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Session Facade

Page 115: JEE Course - EJB

Copyright © Oded Nissan 2009

Session Facade

Page 116: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Session Façade Advantages

Page 117: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Message Facade

Page 118: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Transfer Object

Page 119: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

EJB Command

Page 120: JEE Course - EJB

Copyright © Oded Nissan 2009

The GOF Command Pattern

Page 121: JEE Course - EJB

Copyright © Oded Nissan 2009

EJB Command

Page 122: JEE Course - EJB

Java Persistence API Overview

Copyright © Oded Nissan 2009

Page 123: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

What is ORM ?

Page 124: JEE Course - EJB

Up to the 2.1 spec EJB Entity Beans were the ORM solution in J2EE

However, entity beans were very "heavyweight" and dependent on the application server and the entire Java EE runtime environment.

Lightweight open source ORM frameworks such as Hibernate gained popularity.

Copyright © Oded Nissan 2009

EJB 2.1 Entity Beans

Page 125: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

JPA and EJB 3.0

Page 126: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

JPA Features

Page 127: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Requirements for Entity Classes

Page 128: JEE Course - EJB

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

Copyright © Oded Nissan 2009

Persistence Unit

Page 129: JEE Course - EJB

The persistence context is the set of entities participating in a single unit of work.

These entities are managed by the entity manager.

Copyright © Oded Nissan 2009

Persistence Context

Page 130: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

Entity Manager

Page 131: JEE Course - EJB

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.

Copyright © Oded Nissan 2009

JPQL

Page 132: JEE Course - EJB

Examine the JPA examples

Copyright © Oded Nissan 2009

JPA Examples

Page 133: JEE Course - EJB

What did we discuss ? Overview Session Beans Security Dependency Injection Message Driven Beans (MDB) Transactions EJB Design Patterns Java Persistence API (JPA) Overview

Copyright © Oded Nissan 2009

Summary