Upload
melyssa-jennings
View
41
Download
2
Embed Size (px)
DESCRIPTION
COMS W4156: Advanced Software Engineering. Prof. Gail Kaiser [email protected] http://york.cs.columbia.edu/classes/cs4156/. Java EE 3-Tier Architecture. EJB Specification. - PowerPoint PPT Presentation
Citation preview
25 September 2007 Kaiser: COMS W4156 Fall 2007 1
COMS W4156: Advanced Software Engineering
Prof. Gail Kaiser
http://york.cs.columbia.edu/classes/cs4156/
25 September 2007 Kaiser: COMS W4156 Fall 2007 2
Java EE 3-Tier Architecture
25 September 2007 Kaiser: COMS W4156 Fall 2007 3
EJB Specification
• EJB is an open specification - any vendor can develop a runtime environment that complies with the specification
• EJB specs have been evolving:– Originated with IBM 1997– Later adopted by Sun (1.0 1998, 1.1 1999)– Enhanced under Java community process (2.0 2001,
2.1 2003, 3.0 2006)• EJB 3.0 is a major departure from earlier
versions, but backwards compatible (old code works with 3.0 but not vice versa)
• [Last week < 3.0, today = 3.0]
25 September 2007 Kaiser: COMS W4156 Fall 2007 4
Enterprise Beans
• Encapsulate the business logic of an application
• Now just session and message-driven beans; entity beans are persistence entities that use the Java Persistence API
• Still deployed in an EJB Container (application server) responsible for transaction management, security authorization, etc.
25 September 2007 Kaiser: COMS W4156 Fall 2007 5
Enterprise Bean Class
• Now applies to session beans and message-driven beans but not entities
• Bean type must be specified using metadata annotations (or old XML deployment descriptors)@Stateful public class ShoppingCartBean implements ShoppingCart {
private float total;
private Vector productCodes;
public int someShoppingMethod(){...};
...
25 September 2007 Kaiser: COMS W4156 Fall 2007 6
Business Interfaces
• A business interface is required for both session and message-driven beans, but is now a plain Java interface
• The business interface of a message-driven bean is defined by the messaging type used (typically MessageListener), not by the developer
25 September 2007 Kaiser: COMS W4156 Fall 2007 7
Multiple Interfaces
• If a bean class implements only a single interface (not counting standard interfaces such as java.io.Serializable or any of the javax.ejb interfaces), that is deemed the business interface and is by default a local interface unless designated by a @Remote annotation
• A bean class may have multiple interfaces, but one or more must be designated as a business interface by either a @Local or @Remote annotation (not both)
25 September 2007 Kaiser: COMS W4156 Fall 2007 8
Example@Stateless @Remotepublic class CalculatorBean implements Calculator {
public float add (int a, int b) {return a + b;
}public float subtract (int a, int b) {return a - b;}
}public interface Calculator {
public float add (int a, int b);public float subtract (int a, int b);}
25 September 2007 Kaiser: COMS W4156 Fall 2007 9
Session Bean
• Still represents a single client (not shared) inside the Application Server
• Client still invokes the session bean’s methods to execute business tasks
• Still not persistent (its data is not saved to a database)
• When the client terminates, the session bean still appears to have terminated and is no longer associated with the client
25 September 2007 Kaiser: COMS W4156 Fall 2007 10
Stateful Session Beans
• The instance variables still represent the conversational state of a unique client-bean session
• This state is still retained for the duration of the session across multiple method invocations
• The state still disappears when the client removes the bean or terminates
25 September 2007 Kaiser: COMS W4156 Fall 2007 11
Stateless Session Beans
• Still does not maintain a conversational state• The bean’s instance variables may still contain a
state specific to the client during a single method invocation, but still not retained when the method is finished
• Pooled stateless beans may retain state between invocations, but that state must apply across all clients since all instances of a stateless session bean are still equivalent
25 September 2007 Kaiser: COMS W4156 Fall 2007 12
Session Bean Interfaces
• A client can access a session bean only through the methods in the bean’s business interface
• Can have more than one business interface• A business interface can be either local or
remote (or web service)• No longer a separate home interface - now not
required to implement any lifecycle methods, but may optionally do so and annotate as such
25 September 2007 Kaiser: COMS W4156 Fall 2007 13
Lifecycle Methods• The actual methods can now have any names• @PostConstruct: The container immediately calls the
annotated method after a bean instance is instantiated• @PreDestroy: Called before the container destroys an
unused or expired bean instance from its object pool• @PrePassivate: Called before the container passivates a
stateful bean instance• @PostActivate: Called when a re-activated stateful bean
instance is ready• @Init: Designates initialization methods for a stateful
session bean; the @PostConstruct method, if any, is called afterwards
• @Remove: Informs the container to remove the bean instance from the object pool after the method executes (not actually a callback)
25 September 2007 Kaiser: COMS W4156 Fall 2007 14
Lifecycle of a Stateful Session Bean
• Client initiates the lifecycle by obtaining a reference• Container performs any dependency injection (resolves
annotations) and invokes the @PostConstruct method, if any
• Now bean ready for client to invoke business methods
25 September 2007 Kaiser: COMS W4156 Fall 2007 15
Lifecycle of a Stateful Session Bean
• While in ready state, container may passivate and invoke the @PrePassivate method, if any
• If a client then invokes a business method, the container invokes the @PostActivate method, if any, and it returns to ready stage
25 September 2007 Kaiser: COMS W4156 Fall 2007 16
Lifecycle of a Stateful Session Bean
• At the end of the life cycle, the client invokes a method annotated @Remove
• The container calls the @PreDestroy method, if any
25 September 2007 Kaiser: COMS W4156 Fall 2007 17
Lifecycle of a Stateless Session Bean
• A client initiates the life cycle by obtaining a reference• The container performs any dependency injection and
then invokes the @PostConstruct method, if any• The bean is now ready to have its business methods
invoked by clients
25 September 2007 Kaiser: COMS W4156 Fall 2007 18
Lifecycle of a Stateless Session Bean
• Because a stateless session bean is never passivated, its life cycle has only two stages: nonexistent and ready for the invocation of business methods.
• At the end of the life cycle, the container calls the @PreDestroy method, if any
25 September 2007 Kaiser: COMS W4156 Fall 2007 19
Remote Interfaces
• Support remote clients running on a different JVM or machine, to which is the bean’s location is transparent
• To allow remote access, must decorate the business interface with the @Remote annotation @Remote public interface InterfaceName { ... }
• OR decorate the bean class with @Remote, specifying the business interface(s)@Remote(InterfaceName.class) public class BeanName implements InterfaceName { ... }
25 September 2007 Kaiser: COMS W4156 Fall 2007 20
Local Interfaces
• Client must run in the same JVM as the bean, the location of the bean is not transparent
• Now the default: if the bean’s business interface is not decorated with @Local or @Remote, and the bean class does not specify the interface using @Local or @Remote, the business interface is by default a local interface
25 September 2007 Kaiser: COMS W4156 Fall 2007 21
Local Interfaces
• To build an enterprise bean that allows only local access, optionally annotate the business interface of the enterprise bean as @Local @Local public interface InterfaceName { ... }
• OR specify the interface by decorating the bean class with @Local and specify the interface name@Local(InterfaceName.class) public class BeanName implements InterfaceName { ... }
25 September 2007 Kaiser: COMS W4156 Fall 2007 22
Method Parameters and Return Values
• The parameters of remote calls are more isolated than those of local calls - the client and bean operate on different copies of a parameter object
• If the client changes the value of the object, the value of the copy in the bean does not change
• In a local call, both the client and the bean can modify the same parameter object – but should not rely on this side effect of local calls
• Because remote calls are likely to be slower than local calls, the parameters in remote methods should be relatively coarse-grained
25 September 2007 Kaiser: COMS W4156 Fall 2007 23
Deciding on Local vs. Remote: Coupling
• Tightly coupled beans depend on one another
• For example, if a session bean that processes sales orders calls a session bean that emails a confirmation message to the customer, these beans are tightly coupled
• Tightly coupled beans are good candidates for local access
• Because they fit together as a logical unit, they typically call each other often and would benefit from the increased performance that is possible with local access
25 September 2007 Kaiser: COMS W4156 Fall 2007 24
Deciding on Local vs. Remote: Type of Client
• If an enterprise bean is accessed by application clients, then it should allow remote access
• In a production environment, these clients almost always run on different machines than the Application Server
• If an enterprise bean’s clients are web components or other enterprise beans, then the type of access depends on how you want to distribute your components
25 September 2007 Kaiser: COMS W4156 Fall 2007 25
Deciding on Local vs. Remote: Component Distribution
• Java EE applications are scalable because their server-side components can be distributed across multiple machines
• In a distributed application, the web components may run on a different server than do the enterprise beans they access
• Then the enterprise beans should allow remote access
25 September 2007 Kaiser: COMS W4156 Fall 2007 26
Deciding on Local vs. Remote: Performance
• Due to factors such as network latency, remote calls may be slower than local calls.
• On the other hand, if you distribute components among different servers, you may improve the application’s overall performance
• Actual performance can vary in different operational environments
25 September 2007 Kaiser: COMS W4156 Fall 2007 27
Deciding on Local vs. Remote
• If you aren’t sure which type of access an enterprise bean should have, choose remote access, which gives more flexibility
• In the future you can distribute your components to accommodate the growing demands on your application
• Although it is uncommon, it is possible for an enterprise bean to allow both remote and local access through different interfaces (the same business interface cannot be both a local and remote business interface)
25 September 2007 Kaiser: COMS W4156 Fall 2007 28
Example Stateless Session Bean: Business Interface
…
@Remote
public interface Converter {
public BigDecimal dollarToYen(BigDecimal dollars);
public BigDecimal yenToEuro(BigDecimal yen);
}
25 September 2007 Kaiser: COMS W4156 Fall 2007 29
Example Stateless Session Bean: Enterprise Bean Class
…@Statelesspublic class ConverterBean implements Converter { private BigDecimal yenRate = new BigDecimal("115.3100"); private BigDecimal euroRate = new BigDecimal("0.0071");
public BigDecimal dollarToYen(BigDecimal dollars) { BigDecimal result = dollars.multiply(yenRate); return result.setScale(2, BigDecimal.ROUND_UP); }
public BigDecimal yenToEuro(BigDecimal yen) { BigDecimal result = yen.multiply(euroRate); return result.setScale(2, BigDecimal.ROUND_UP); }}
25 September 2007 Kaiser: COMS W4156 Fall 2007 30
Example Stateless Session Bean: Application Client
…public class ConverterClient { @EJB private static Converter converter; public ConverterClient(String[] args) { }
public static void main(String[] args) { ConverterClient client = new ConverterClient(args); client.doConversion(); }
25 September 2007 Kaiser: COMS W4156 Fall 2007 31
Example Stateless Session Bean: Application Client
public void doConversion() { try { BigDecimal param = new BigDecimal("100.00"); BigDecimal yenAmount = converter.dollarToYen(param); System.out.println("$" + param + " is " + yenAmount + "
Yen."); BigDecimal euroAmount = converter.yenToEuro(yenAmount); System.out.println(yenAmount + " Yen is " + euroAmount +
" Euro."); System.exit(0); } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); }}}
25 September 2007 Kaiser: COMS W4156 Fall 2007 32
Example Stateful Session Bean: Business Interface
…@Remotepublic interface Cart { public void initialize(String person) throws
BookException; public void initialize(String person, String id) throws BookException; public void addBook(String title); public void removeBook(String title) throws
BookException; public List<String> getContents(); public void remove();}
25 September 2007 Kaiser: COMS W4156 Fall 2007 33
Example Stateful Session Bean: Enterprise Bean Class
…@Statefulpublic class CartBean implements Cart { String customerName; String customerId; List<String> contents;
public void initialize(String person) throws BookException {
if (person == null) { throw new BookException("Null person not
allowed."); } else { customerName = person; } customerId = "0"; contents = new ArrayList<String>(); }
25 September 2007 Kaiser: COMS W4156 Fall 2007 34
Example Stateful Session Bean: Enterprise Bean Class
public void initialize(String person, String id) throws BookException { if (person == null) { throw new BookException("Null person not
allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new BookException("Invalid id: " + id); } contents = new ArrayList<String>(); }
25 September 2007 Kaiser: COMS W4156 Fall 2007 35
Example Stateful Session Bean: Enterprise Bean Class
public void addBook(String title) { contents.add(title); }
public void removeBook(String title) throws BookException { boolean result = contents.remove(title); if (result == false) { throw new BookException(title + " not in cart."); } }
public List<String> getContents() { return contents; }
@Remove public void remove() { contents = null; }}
25 September 2007 Kaiser: COMS W4156 Fall 2007 36
Message-Driven Beans
• Allows Java EE applications to process messages asynchronously (session beans can receive synchronous messages)
• Acts as a JMS (Java Message Service) message listener• Messages can be sent by an application client, another
enterprise bean, a web component, or a JMS system that does not use Java EE technology
25 September 2007 Kaiser: COMS W4156 Fall 2007 37
What is Messaging?
• A method of communication between software components or applications
• A messaging client can send messages to, and receive messages from, any other client
• Each client connects to a messaging agent that provides facilities for creating, sending, receiving and reading messages
25 September 2007 Kaiser: COMS W4156 Fall 2007 38
What is Messaging?
• Messaging enables distributed communication that is loosely coupled
• A component sends a message to a destination, and the recipient retrieves the message from the destination
• However, the sender and the receiver do not have to be available at the same time
• The sender does not need to know anything about the receiver, nor vice versa
• Both only need to know which message format and which destination to use
• Differs from tightly coupled technologies, such as Remote Method Invocation (RMI), which require an application to know a remote application’s methods
25 September 2007 Kaiser: COMS W4156 Fall 2007 39
JMS API
• Common set of interfaces and associated semantics that allow programs written in Java to communicate with other messaging implementations
• The JMS API can ensure that a message is delivered once and only once (PERSISTENT)
• Lower reliability, at most once (NON_PERSISTENT), is available for applications that can afford to miss messages
25 September 2007 Kaiser: COMS W4156 Fall 2007 40
JMS API Architecture
• A JMS provider is a messaging system that implements the JMS interfaces and provides administrative and control features (included in Java EE)
• JMS clients are the programs or components that produce and consume messages
• Messages are the objects that communicate information between JMS clients
• Administered objects are preconfigured JMS objects (destinations and connection factories) created by an administrator for the use of clients
25 September 2007 Kaiser: COMS W4156 Fall 2007 41
JMS API Architecture
25 September 2007 Kaiser: COMS W4156 Fall 2007 42
Messaging Domains
• Either point-to-point or publish/subscribe
• JMS API provides common interfaces not specific to either domain
25 September 2007 Kaiser: COMS W4156 Fall 2007 43
Point-to-Point
• Built on the concept of message queues, senders and receivers
• Each message is addressed to a specific queue, and receiving clients extract messages from the queues established to hold their messages
• Queues retain all messages sent to them until the messages are consumed or until the messages expire
25 September 2007 Kaiser: COMS W4156 Fall 2007 44
Point-to-Point
• Each message has only one consumer• A sender and a receiver of a message have no timing
dependencies - the receiver can fetch the message whether or not it was running when the client sent the message
• The receiver acknowledges the successful processing of a message
25 September 2007 Kaiser: COMS W4156 Fall 2007 45
Publish/Subscribe• Clients address messages to a topic• Each message can have multiple consumers.• Publishers and subscribers are anonymous and can
dynamically publish or subscribe to the content hierarchy• The system distributes the messages arriving from a
topic’s multiple publishers to its multiple subscribers• Topics retain messages only as long as it takes to
distribute them to current subscribers.
25 September 2007 Kaiser: COMS W4156 Fall 2007 46
Publish/Subscribe
• Publishers and subscribers have a timing dependency – a client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages
• JMS relaxes this timing dependency by allowing durable subscriptions, which receive messages sent while the subscribers are not active
25 September 2007 Kaiser: COMS W4156 Fall 2007 47
Message Consumption
• Synchronous: A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method - the receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit
• Asynchronous: A client can register a message listener with a consumer - Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message
25 September 2007 Kaiser: COMS W4156 Fall 2007 48
Programming Model
25 September 2007 Kaiser: COMS W4156 Fall 2007 49
Connection Factory
• The object a client uses to create a connection to a provider
• Encapsulates a set of configuration parameters defined by an administrator
• At the beginning of a JMS client program, you inject a connection factory resource into a ConnectionFactory object
@Resource(mappedName="jms/ConnectionFactory") private static ConnectionFactory connectionFactory;
25 September 2007 Kaiser: COMS W4156 Fall 2007 50
Destination
• The object a client uses to specify the target of messages it produces and the source of messages it consumes
• In PTP, destinations are called queues• In pub/sub, destinations are called topics• To create a destination using the Application Server,
create a JMS destination resource that specifies a JNDI name for the destination
@Resource(mappedName="jms/Queue") private static Queue queue;
@Resource(mappedName="jms/Topic") private static Topic topic;
25 September 2007 Kaiser: COMS W4156 Fall 2007 51
And many more details…
25 September 2007 Kaiser: COMS W4156 Fall 2007 52
Back to Message-Driven Beans
• Allows Java EE applications to process messages asynchronously (session beans can receive synchronous messages)
• Acts as a JMS message listener• Messages can be sent by an application client, another
enterprise bean, a web component, or a JMS system that does not use Java EE technology
25 September 2007 Kaiser: COMS W4156 Fall 2007 53
How are Message-Driven Beans Different from Session Beans?
• Clients do not access through interfaces• Developer does not define any interfaces, only a bean
class that implements the MessageListener interface• Otherwise resembles a stateless session bean:
– Retains no data or conversational state for a specific client– All instances equivalent, allowing EJB container to assign a
message to any bean instance in a pool– Can process messages from multiple clients (one at a time)– Client-independent state can be retained across messages (e.g.,
JMS API connection, open database connection, object reference to an enterprise bean)
25 September 2007 Kaiser: COMS W4156 Fall 2007 54
Sending Messages
• Clients do not locate message-driven beans and invoke methods on them directly
• Instead client sends the message to a message destination for which the message-driven bean class is a MessageListener (assigned during deployment)
• Message may be delivered within a transactional context, so if that transaction is rolled back the message will be redelivered
25 September 2007 Kaiser: COMS W4156 Fall 2007 55
Receiving Messages
• When a message arrives, the container calls the bean’s onMessage method
• This method casts the message to one of the five JMS message types (text, map, bytes, stream, object)
• Can call helper methods or invoke a session bean to process the message
25 September 2007 Kaiser: COMS W4156 Fall 2007 56
Lifecycle of a Message-Driven Bean
• The container usually creates a pool of message-driven bean instances
• For each, the container performs dependency injection, if any, and calls the @PostConstruct method, if any
25 September 2007 Kaiser: COMS W4156 Fall 2007 57
Lifecycle of a Message-Driven Bean
• A message-driven bean is never passivated, and it has only two states: nonexistent and ready to receive messages
• At the end of the life cycle, the container calls the @PreDestroy method, if any
25 September 2007 Kaiser: COMS W4156 Fall 2007 58
Example Message-Driven Bean:Application Client
@Resource(mappedName="jms/ConnectionFactory")private static ConnectionFactory connectionFactory;
@Resource(mappedName=”jms/Queue”)private static Queue queue;
connection = connectionFactory.createConnection();session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);messageProducer = session.createProducer(queue);
message = session.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); messageProducer.send(message);
25 September 2007 Kaiser: COMS W4156 Fall 2007 59
Example Message-Driven Bean:Enterprise Bean Class
@MessageDriven(mappedName="jms/Queue")public class SimpleMessageBean implements MessageListener {
@Resource private MessageDrivenContext mdc;…
25 September 2007 Kaiser: COMS W4156 Fall 2007 60
Example Message-Driven Bean:Enterprise Bean Class
public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; logger.info("MESSAGE BEAN: Message received: " + msg.getText()); } else { logger.warning("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { te.printStackTrace(); }}}
25 September 2007 Kaiser: COMS W4156 Fall 2007 61
What Happened to Entity Beans?
• Now called persistence entities or just entities• Uses the Java Persistence API• Annotated with @Entity• No longer needs to conform to the enterprise
beans specifications• The entity class still represents a table in a
relational database• An entity instance still represents a row in that
table
25 September 2007 Kaiser: COMS W4156 Fall 2007 62
Instance Variables
• Persistent instance variables still can only be accessed through the entity class’ methods
• Still must only be serializable types (so they can be stored in a database)
• Object/relational mapping still must be defined, now using annotations
• Still may include non-persistent instance variables, now annotated as @Transient
• May also use single-valued and collection-valued persistent properties, with getters and setters
25 September 2007 Kaiser: COMS W4156 Fall 2007 63
Primary Keys• Each entity still must have a unique object
identifier, which may be either simple or composite• Simple primary keys now annotated @Id• Composite primary keys defined by a primary key
class, annotated @IdClass (or @EmbeddedId if embeddable)
• The simple primary key, or each field of a composite primary key, must be a Java primitive type, string or date
• Use EntityManager.find method used to look up entities by primary key
25 September 2007 Kaiser: COMS W4156 Fall 2007 64
Queries
• Other finder methods defined using SQL-like queries in Java Persistence Query Language - replaces Enterprise JavaBeans Query Language (EJB QL) in EJB 3.0
• EntityManager.createQuery method used to create dynamic queries defined within business logicpublic List findWithName(String name) {return em.createQuery( "SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter("custName", name) .setMaxResults(10) .getResultList();}
25 September 2007 Kaiser: COMS W4156 Fall 2007 65
Queries
• EntityManager.createNamedQuery method used to create static queries defined in annotation metadata@NamedQuery( name="findAllCustomersWithName", query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)customers = em.createNamedQuery("findAllCustomersWithName")
.setParameter("custName", "Smith") .getResultList();
25 September 2007 Kaiser: COMS W4156 Fall 2007 66
Entity Relationships
• Multiplicity relationships still supported, now denoted with annotations: @OnetoOne, @OneToMany, @ManyToOne, @ManyToMany
• Bidirectional relationships: owning side and inverse side (mappedBy)
• Unidirectional relationships: only owning side• OneToOne and OneToMany may have cascade
delete relationships (cascade=REMOVE)
25 September 2007 Kaiser: COMS W4156 Fall 2007 67
Managing Entities
• Entity Manager represented by javax.persistence.EntityManager instances
• Associated with a persistence context corresponding to a particular data store@PersistenceContext public EntityManager em;
• Both Container-Managed Entity Managers (automatic) and Application-Managed Entity Managers
25 September 2007 Kaiser: COMS W4156 Fall 2007 68
Transactions
• State of persistent entities still automatically synchronized to the database when the associated transaction commits
• But business logic for transactions still resides in session or message-driven beans
• Either container-managed or bean-managed transactions
25 September 2007 Kaiser: COMS W4156 Fall 2007 69
Container-Managed Transactions
• Container sets the boundaries of transactions, cannot use operations like commit or rollback within code (but can invoke the getRollbackOnly and setRollbackOnly methods of the EJBContext interface)
• Container begins transaction immediately before enterprise bean method starts and commits just before method exits
• Decorate entire enterprise bean class or individual business method with @TransactionAttribute
• Same transaction types: Required, RequiresNew, Mandatory, NotSupported, Supports, Never
25 September 2007 Kaiser: COMS W4156 Fall 2007 70
Example@TransactionAttribute(NOT_SUPPORTED)@Statefulpublic class TransactionBean implements Transaction
{... @TransactionAttribute(REQUIRES_NEW) public void firstMethod() {...}
@TransactionAttribute(REQUIRED) public void secondMethod() {...}
public void thirdMethod() {...}
public void fourthMethod() {...}}
25 September 2007 Kaiser: COMS W4156 Fall 2007 71
Bean-Managed Transactions
• The code in the session or message-driven bean explicitly marks the boundaries of the transaction
• Useful for implementing multiple transactions within a single method or transactions than span multiple methods
• Can use either JDBC or the Java Transaction API (JTA)• A JTA transaction can span updates to multiple
databases from different vendors managed by the Java Transaction Service, but cannot support nested transactions
• JTA supplies begin, commit and rollback methods
25 September 2007 Kaiser: COMS W4156 Fall 2007 72
Using Transactions in Session Beans
• A stateless session bean with bean-managed transactions must commit or roll back before returning
• A stateful session bean using JTA transactions retains its association with a transaction across multiple client calls, even if the database connection is opened and closed
• A stateful session bean using JDBC transactions loses its transaction association if the connection is closed
25 September 2007 Kaiser: COMS W4156 Fall 2007 73
Saving a Session Bean’s State in a Database
• Transactions normally concerned with synchronizing the state of persistent entities to databases
• Optional for a stateful session bean to receive transaction synchronization notifications to also store its own data in a database
• Then must implement the SessionSynchronization interface, supplying afterBegin, beforeCompletion and afterCompletion methods
25 September 2007 Kaiser: COMS W4156 Fall 2007 74
And Much More…
25 September 2007 Kaiser: COMS W4156 Fall 2007 75
EJB 3.0 Simplified API
• EJB 2.1 APIs remain available and components written to those APIs may be used in conjunction with components written to the new EJB 3.0 APIs
• Use of Java language metadata annotations to reduce the number of program classes and interfaces the developer is required to implement, and to eliminate the need to provide an EJB deployment descriptor
• Specification of defaults to reduce the need to specify common, expected behaviors and requirements on the EJB container - “configuration by exception” approach
• Encapsulation of environmental dependencies and JNDI access through the use of annotations, dependency injection mechanisms, and simple lookup mechanisms
25 September 2007 Kaiser: COMS W4156 Fall 2007 76
EJB 3.0 Simplified API
• Simplification of the enterprise bean types• Elimination of the requirement for EJB component
interfaces for session beans – the required business interface for a session bean can be a plain Java interface
• Elimination of the requirement for home interfaces for session beans
• Simplification of entity persistence through the Java Persistence API
• Support for light-weight domain modeling, including inheritance and polymorphism
• Elimination of all required interfaces for persistent entities
25 September 2007 Kaiser: COMS W4156 Fall 2007 77
EJB 3.0 Simplified API• Use Java language metadata annotations and XML
deployment descriptor elements for the object/relational mapping of persistent entities
• A query language for Java Persistence that is an extension to EJB QL, with addition of projection, explicit inner and outer join operations, bulk update and delete, subqueries, and group-by
• Addition of a dynamic query capability and support for native SQL queries
• An interceptor facility for session beans and message-driven beans
• Reduction of the requirements for usage of checked exceptions
• Elimination of the requirement for the implementation of callback interfaces
25 September 2007 Kaiser: COMS W4156 Fall 2007 78
IDA #3 Due Next Week!
• Tuesday 2 October, 10am
• Assignments posted on course website
• Submit via CourseWorks
• Individual Development Assignment #3
25 September 2007 Kaiser: COMS W4156 Fall 2007 79
Upcoming Deadlines
• Revised project concept due October 9th – first iteration begins
• First iteration plan due October 16th • First iteration progress report due October 23rd • First iteration demo week October 30th –
November 8th • First iteration final report due November 9th
25 September 2007 Kaiser: COMS W4156 Fall 2007 80
COMS W4156: Advanced Software Engineering
Prof. Gail Kaiser
http://york.cs.columbia.edu/classes/cs4156/