Sun Certified Enterprise Architect for Java 2 Study Notes Topic: EJB (Enterprise JavaBeans) Objectives: 1. List the required classes/interfaces that must be provided for an EJB. 2. Distinguish stateful and stateless Session beans 3. Distinguish Session and Entity beans 4. Recognize appropriate uses for Entity, Stateful Session, and Stateless Session beans 5. State benefits and costs of Container Managed Persistence 6. State the transactional behavior in a given scenario for an enterprise bean method with a specified transactional attribute as defined in the deployment descriptor 7. Given a requirement specification detailing security and flexibility needs, identify architectures that would fulfill those requirements 8. Identify costs and benefits of using an intermediate data-access object between an entity bean and the data resource 9. State the benefits of bean pooling in an EJB container 10. State the benefits of passivation in an EJB container 11. State the benefit of monitoring of resources in an EJB container 12. Explain how the EJB container does lifecycle management and has the capability to increase scalability References: Symbol: Reference: JENS Java Enterprise In a Nutshell, Flanagan, Farley, Crawford, & Magnusson, O’Reilly, 1999. MEJB Mastering Enterprise JavaBeans, Ed Roman, Wiley, 1999 EJB Enterprise JavaBeans 2nd Edition, Monson-Haefel, O’Reilly, 2000 ** OBJECTIVE #1: List the required classes/interfaces that must be provided for an EJB. - For all types of EJBs, you need to provide three Java interfaces/classes to fully describe the EJB to an EJB container: 1. The HOME INTERFACE which takes the form: import javax.ejb.*; import java.rmi.RemoteException; public interface MyHomeInterface extends EJBHome { public MyRemoteInterface create() throws RemoteException; .... } 2. The REMOTE INTERFACE which takes the form: import javax.ejb.*; import java.rmi.RemoteException; public interface MyRemoteInterface extends EJBObject { // business method definitions all of which can throw // a RemoteException } 3. The BEAN CLASS itself, which takes two forms: -> For Session Beans: import javax.ejb.*; import java.rmi.RemoteException; public class MyBean implements SessionBean { // required methods public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext() {} // business method implementations } -> For Entity Beans: import javax.ejb.*; import java.rmi.RemoteException; public class MyBean implements EntityBean { // entity bean methods see EJNS p.199 for details } 4. Additionally, for ENTITY BEANS, you must also provide a PRIMARY KEY CLASS, which takes the form: import javax.ejb.*; public class MyBeanPK implements java.io.Serializable { public String someFieldToUseAsPK; public MyBeanPK() { someFieldToUseAsPK = null; } public MyBeanPK(String s) { someFieldToUseAsPK = s; } } - Primary key - The primary key can only be guaranteed to return the same entity if it is used within the container that produced the key. - If two EJB objects have the same home and same PK they are considered identical. - A primary key must implement the Serializable interface. - EJB 1.1 requires that the hashCode and equals methods be overridden. - EJB 1.1 allows the PK to be defined by the bean developer or its definition can be deferred until deployment. - A default (no-arguments) PK constructor is required for CMP. When a new bean is created the container automatically instantiates the PK, and populates it from the bean class’s CMP fields. - All fields in the PK class must be declared public. - The String class and the wrapper classes for the primitive data types can also be used as PKs. In this case there is no explicit PK class. However, there must still be an identifiable primary key within the bean class itself. (there are some special rules for this primary key class when using container managed persistence. See EJNS p.197) ** OBJECTIVE #2: Distinguish stateful and stateless Session beans - Session beans can be either stateless of stateful. - Stateless Session beans do not maintain state across method calls. The Session bean returns to the same state after each successive call to one of its methods from a client. This makes a stateless Session bean poolable for performance and accessible from multiple clients (one at a time) without fear of conflict. Stateless Session beans are never passivated, but just destroyed (or removed from the pool) when no longer needed. Stateless beans cannot participate in any transaction synchronization (e.g. implement interface SessionSynchronization). A stateless session bean is only dedicated to an EJB object for the duration of the method. - Stateful Session beans maintain a state that can be accessed and changed across multiple client interactions with the bean’s methods. Stateful Session beans are accessed by only a single client and can be passivated by the container. At deployment time, you indicate to the container whether a Session bean is stateful or stateless with an identifier in the deployment descriptor. ** OBJECTIVE #3: Distinguish Session and Entity beans - There are two types of beans in the EJB specification, Session and Entity beans. - Session beans represent business logic, rules, and workflow. They perform some sort of work for the client that is calling them. Important features of Session beans: 1. Two types, stateful and stateless (see last objective above) 2. Never used by more than one client at a time 3. Lifetime is roughly the same as the period during which the client interacts with the bean - Entity beans represent data that is stored in a database or some persistent storage. Important features of Entity beans: 1. Persistent across client sessions and the lifetime of the server 2. Have a unique identity used for lookup 3. Multiple clients can access at once the container manages this concurrency. 4. Persistence of the data the bean represents is either container or bean - managed ** OBJECTIVE #4: Recognize appropriate uses for Entity, Stateful Session, and Stateless Session beans - Entity beans do not contain business process logic; they model data. Examples of persistent data include things like account, customer, order line, etc. - Session beans model business processes such as performing a credit card verification, reserving a room, etc. Some processes require a single method call (stateless) to complete, while other processes may require repeated calls that require storing state information across these calls (stateful). An example of a stateful process would be a bean that tracks an on-line shopper’s cart, the contents of which must be maintained across multiple calls to the bean. Code that represents a bank teller interacting with a customer might also need to track account balance or credit limit across multiple banking transactions in a single interaction with the customer. - Recognizing the type of bean to use begins by asking, "is this a process or a persistent thing I’m working with" (session versus entity) and if it is a process, asking "is this a single method call with no need to reference prior state or do I need multiple transactions with a stored state to accomplish this process?" (stateless versus stateful). ** OBJECTIVE #5: State benefits and costs of Container Managed Persistence - Container Managed Persistence (CMP) refers to an EJB container providing automatic persistence for Entity beans. The container performs all aspects of data access for the entity bean, including saving, loading, and finding components of the data. - Stated Benefits: (nets out to: rapid application dev and portability) - Database Independence: No need to hard code against a specific database API to accomplish these things Code Reduction: CMP performs all data access logic without the need to write any JDBC code, reducing the amount of code needed and hence development time for the bean. - Enhances Software Quality: JDBC code is not type-safe and is frequently buggy because it cannot be verified until runtime. - The developer who wrote the container likely writes better data access code than you do and usually provides contained tools that allow detecting of errors at compile time. The better the container, the more your Entity bean code improves in quality. - Real Life Costs: (nets out to: limits flexibility, portability not 100%) - Not all containers require you to write absolutely zero persistence code. Most containers at least require you to navigate a wizard to specify persistent fields and that you specify the logic for your finder methods. - If there is a bug, it is hard to see what database operations the container is actually executing in order to troubleshoot the problem. - Some containers may not support mapping of complex field types to underlying storage. Example: your entity bean class has a vector as a persistent member field. You may have to convert this vector to some other type that the container can persist for you. - Portability across databases is not yet perfect. Specifying persistence semantics is not standardized yet and what BEA requires you to do to map your objects to relational fields may be inconsistent with another container vendor. If mapping your objects to relational tables is not 1:1 or you need complicated SQL joins in finder methods, some containers lack the ability to handle this. - May require sophisticated mapping tools to define how the bean’s fields map to the database. - EJB 1.1 allows the CMP fields to include remote references to EJB objects (remote interface types) and EJB homes (home interface types). EJB 1.0 only allowed Java primitives and serializable types. - Data Aliasing - Eager State Loading ** OBJECTIVE #6: State the transactional behavior in a given scenario for an enterprise bean method with a specified transactional attribute as defined in the deployment descriptor - Transactional attributes of bean methods are specified in the deployment descriptor. Here are the attributes and what they mean (MEJB p.706): - TX_BEAN_MANAGED The bean programmatically controls it’s own tx. EJB 1.0 Only boundaries via JTA. - NOTSUPPORTED The bean CANNOT be involved in a transaction at all. When a bean method is called, any existing tx is suspended. - REQUIRED The bean must ALWAYS run in a transaction. If a tx is already running, the bean joins in that tx. If not, the container starts a tx for you. - REQUIRESNEW The bean must ALWAYS run in a NEW transaction. Any current tx is suspended. VALIDATE THIS FOR "REQUIRESNEW" Supports If a transaction is underway, the bean joins in that tx, otherwise runs with no tx at all. - MANDATORY Mandates that a transaction must already be running when the bean method is called or an exception is thrown back to the caller. - NEVER If a tx is underway the bean will throw a EJB 1.1 Only RemoteException, otherwise the method Runs normally without a tx. ** OBJECTIVE #7: Given a requirement specification detailing security and flexibility needs, identify architectures that would fulfill those requirements. - Security: EJB servers can provide up to three types of security service: 1. Authentication: validates the identity of the user, usually via JNDI: A client using JNDI can provide authenticating information using the JNDI API to access a server or resources in the server. 2. Access Control: validates what the user can and cannot do. EJB 1.1 changed authorization to be based on java.security.Principal types rather than Identity types and to be role-driven rather than method-driven. - Deployment descriptors include tags that declare which logical roles are allowed to access which bean methods at runtime. - Security roles are mapped to real-world user groups and users when the bean is deployed. Once the security-role tags are declared they can be associated with methods in the bean using method-permission tags. 3. Secure Communication: client server communication channels can be secured by physical isolation or encrypting the conversation - usually via SSL. Encryption usually involves the exchange of keys to decode the encrypted data. Most EJB servers address Secure Communications through SSL encryption and also provide some mechanism such as JNDI for Authentication. The EJB 1.1 Specification only addresses Access Control on the server side. - For a complete discussion of J2EE security services and topics like Role-Driven versus Method-Driven access control, see EJB Chap 3: Security (p.71). ** OBJECTIVE #8: Identify costs and benefits of using an intermediate data-access object between an entity bean and the data resource. - EJBs are remote objects that consume significant system resources and network bandwidth. You can use Data Access Objects to encapsulate the logic required to access databases. - Data Access Objects: - Allow EJBs to delegate responsibility for database access and free them from complex data access routines. - Make code more maintainable. - Provide an easier migration path to CMP - Allow you to adapt data access to different schemas and different databases. ** OBJECTIVE #9: State the benefits of bean pooling in an EJB container. - EJB clients interact with remote interfaces that are implemented by EJB Object instances. This indirect access to the bean instance means that there is no fundamental reason to keep a separate copy of each bean for each client. The server can keep a much smaller number of beans instantiated in a pool that serves a large number of clients. The container simply copies data into or out of these pooled instances as necessary. - Benefit: greatly reduces the server resources required to serve the same number of clients. ** OBJECTIVE #10: State the benefits of passivation in an EJB container. - An EJB container can choose to temporarily serialize a bean and store it to the server filesystem or other persistent store so that it can optimally manage resources. This is called passivation. The benefit of passivation is to allow the EJB container to make the best possible use of server resources by passivating a bean to free up resources and then re-activating it when resources are available. - A session bean can be passivated only between transactions, and not within a transaction. ** OBJECTIVE #11: State the benefit of monitoring of resources in an EJB container. - An EJB container can achieve greater levels of performance and scalability by monitoring server resources and using techniques to share resources (such as instance pooling and activation/passivation) and also techniques to synchronize object interactions (such as managing concurrency, and transactional control) to optimally serve remote objects to clients. ** OBJECTIVE #12: Explain how the EJB container does lifecycle management and has the capability to increase scalability. - The EJB container uses two fundamental strategies to perform lifecycle management, instance pooling and passivation/activation. - Instance pooling reduces the number of component instances, and therefore resources, needed to service client requests. In addition, it is less expensive to reuse pooled instances than to frequently create and destroy instances. Since clients never access beans directly there’s no real reason to keep a separate copy of each bean for each client. EJB Containers implement instance pooling (a significant performance and scalability strategy) by managing the lifecycle of beans. An entity bean exists in one of three states: 1. No State (has not been instantiated yet) 2. Pooled State (instantiated by not associated with the EJB Object) 3. Ready State (instantiated and associated). If a client request is received and no entity bean instance is associated with the EJB Object connected to the client, an instance is retrieved from the pool and assigned to the EJB Object. Once an instance is assigned to an EJB object the ejbActivate method is called. This is called instance swapping. Instances are selected based on the vendor’s choice of a FIFO or LILO strategy. The container can manage the number of instances in the pool and hence control performance. When an entity bean instance is activated, transient fields contain arbitrary values and must be reset in the ejbActivate method. For a CMP bean the CMP fields are automatically synchronized with the database after ejbActivate has been invoked. In BMP after ejbActivate has completed you use the ejbLoad method to synchronize fields. - Entity beans can be passivated at any time provided the instance is not currently executing a method. Passivation of an entity bean is simply a notification that the instance is about to be disassociated from the EJB object. Stateful Session Beans maintain a conversational state between method invocations. The container must maintain this conversational state for the life of the bean’s service to the client. Stateful Session beans do not participate in instance pooling but rather the container may choose to evict a stateful Session bean from memory to conserve resources. The bean is passivated (i.e. has it’s state serialized to disk) and disassociated with the EJB Object. The client is completely unaware of this performance move on the part of the container. When the client invokes another method on the EJBObject, a new instance is created and populated with the passivated state (called activation). The ejbPassivate method is called immediately prior to passivation of a bean instance. The ejbActivation method is called immediately following the successful activation of a bean instance. ** Additional Notes - The EJB architecture is an architecture for component-based distributed computing. EJBs are components of distributed transaction-oriented enterprise applications. - Enterprise beans are intended to be relatively coarse-grained business objects (purchase order, employee record). Fine-grained objects (line item on a purchase order, employee’s address) should not be modeled as enterprise bean components. ** Stateful Session - Sun’s EJB 1.1 spec states Session beans are intended to be stateful. The EJB specification also defines a stateless Session bean as a special case of a Session Bean. There are minor differences in the API between stateful (normal) Session benas and stateless Session beans. - A typical (stateful) session object has the following characteristics: - Executes on behalf of a single client. It is not shared among multiple clients. - Do not support concurrent access. - Can be transaction-aware - Updates shared data in an underlying database - Does NOT represent directly shared data in the database, although it may. - Access and update that data - Is relatively short-lived - Is removed when the EJB container crashes. The client has to re-establish a new session object to continue computation - By definition, a session bean instance is an extension of the client that creates it: - Its fields contain a conversational state on behalf of the session object’s client. - It typical reads and updates data in a database on behalf of the client. Within a transaction, some of this data may be cached in the instance. - Its lifetime is controlled by the client. - Find methods are not used in session beans. - When a remove method is called on a session bean it ends the bean’s service to the client. The remote reference becomes invalid and any conversational state maintained by the bean is lost. - As soon as the server removes a stateful session bean its handle is invalid and will throw a RemoteException when its getEJBObject() method is invoked. - A stateful session object has a unique identity that is assigned by the container at create time. This identity, in general, does not survive a crash and restart of the container, although a high-end container impl can mask container and server crashes from the client. Session objects appear to be anonymous to a client. - If a timeout occurs the ejbRemove() method is not called. A stateful session bean cannot time out while a transaction is in progress. A session bean can timeout while it is passivated. - A stateful session bean cannot be removed while it is involved in a transaction. - The home interface allows a client to obtain a handle for the home interface. The home handle can be serialized and written to storage. Later, possibly in a different JVM, the handle can be de-serialized from storage and used to obtain a reference to the home interface. When the handle is later de-serialized, the session object it returns will work as long as the session object still exists on the server. (An earlier timeout or server crash may have destroyed the session object. In this case the handle is useless.) - Typically, a session object’s conversational state is not written to the database. A session bean developer stores it in the session bean instance’s fields and assumes its value is retained for the lifetime of the instance. On the other hand, the session bean must explicitly manage cached database data. (It can do this when participating in a transaction.) A session object’s conversational state may contain open resources, such as open sockets and open database cursors. A container cannot retain such open resources when a session bean instance is passivated. A developer of such a session bean must close and open the resources in the ejbPassivate and ejbActivate methods. As an example, the ejbPassivate method must close all JDBC connections and assign the instance’s fields that store these connections to null. - In EJB 1.1 when a bean is passivated the following types may be saved as part of the conversational state: - JNDI ENC (javax.naming.Context, but only when it references the JNDI ENC) - references to SessionContext, - refs to other beans (home & remote i/fs) - the JTA UserTransaction type. - The container must maintain any instance fields that reference objects of these types as part of the conversational state even if they are not serializable. Primitive types and serializable objects can also be part of the conversational state. - In EJB, transient fields are not necessarily set back to their initial values but can maintain their original values, or any arbitrary value, after being activated. Care should be taken when using transient fields, since their state following activation is implementation independent. The ejbActivate method is called following the successful activation of a bean instance and can be used to reset transient field values. - If the EJB container crashes, or a system exception is thrown by a method to the container, or a timeout occurs while the the bean is passivated then ejbRemove will not be invoked. This means any allocated resources will not be released. - A session object’s conversational state is not transactional. It is not automatically rolled back to its initial state if the transaction in which the object has participated rolls back. The developer must use the afterCompletion method to manually reset the state. - Only a stateful session bean with container-managed transaction demarcation may implement the SessionSynchronization interface. This means that the bean can cache database data across several method calls before making an update. - Clients are not allowed to make concurrent calls to a session object. This will cause a remote exception to be thrown to the second client. - A RuntimeException thrown from any method of a stateful session bean results in a transition to the "does not exist" state. From the client perspective, the corresponding stateful session object does not exist anymore. Subsequent calls through the remote interface will result in NoSuchObjectExceptions. - Calls to a session bean that has had ejbRemove invoked on it will result in NoSuchObjectExceptions. - Calls to a session bean that has timed out will result in NoSuchObjectExceptions. ** Stateless Session beans - Stateless Session beans have no conversational state. All stateless session bean instances are equivalent when they are not involved in serving a client-invoked method. - The home interface of all stateless session beans contains one create() method with no arguments. This is a requirement of the EJB spec. This means that the bean class only has one ejbCreate() method. (The ejbCreate method is not actually invoked by the create method.) - A timeout or remove operation simply invalidates the remote reference for the client. The bean instance is not destroyed and is free to service other client requests. - The term "stateless" signifies that an instance has no state for a specific client. However, the instance variables of the instance can contain state across client-invoked calls. An example is a database connection. - Everything that a stateless session bean needs to know to perform an operation has to be passed via the method’s parameters. - Calling getPrimaryKey on a stateless session bean will cause a RemoteException to be thrown. - Calling remove(primaryKey) on a stateless (or stateful) session bean will cause a RemoteException to be thrown. - Passivation and Activation are not needed for stateless session beans. - All session objects of the same stateless session bean within the same home have the same object identity that is assigned by the container. - Applications that use stateless session beans may scale somewhat better than those using stateful session beans. However, this benefit may be offset by the increased complexity of the client application that uses stateless beans. - A stateless session bean must not implement the SessionSynchronization interface. - A RuntimeException thrown from any method of a stateless session bean results in a transition to the "does not exist" state. From the client perspective, the stateless session object continues to exist. The client can continue accessing the session object because the container can delegate the client’s requests to another instance. ** Entity Beans - Entity: A typical entity object has the following characteristics: - Provides an object view of data in the database - Allows shared access from multiple users - Can be long-lived (lives as long as the data in the database) - The entity, its primary key, and its remote reference survive the crash of the EJB container. If the state of an entity was being updated by a transaction at the time the container crashed, the entity’s state is automatically reset to the state of the last committed transaction. The crash is not fully transparent to the client the client may receive an exception if it calls an entity in a container that has had a crash. - A good rule of thumb is that entity beans model business concepts that can be expressed as nouns. They are usually persistent records in a database. - Constructors should never be defined in the bean class. The default ctor must be available to the container. (It is automatically generated for a class if no ctors are provided.) - In EJB 1.1 the ejbCreate() method always returns the primary key type. With CMP this method returns null. It is the container’s responsibility to create the primary key. - The findByPrimaryKey() method is not defined for CMP entity beans. With CMP you do not explicitly declare find methods in the bean class. The EJB container generates the find methods automatically at deployment time. In CMP any find method included in the home interface must be explained to the container. - With BMP entity beans find methods must be defined in the bean class. - When a remove method is invoked on an entity bean, the remote reference becomes invalid and any data that it represents is deleted from the database. - The entity bean’s persistence can be implemented directly in the entity bean class or in one or more helper classes (Data Access Objects) provided with the entity bean class (BMP) or it can be delegated to the container (CMP). - Directly coding the data access calls in the entity bean class may make it more difficult to adapt the entity bean to work with a database that has a different schema or with a different type of database. Use of a DAO could allow adapting the data access to different schemas or databases. - The advantage of using CMP is that the entity bean can be largely independent from the data source in which the entity is stored. CMP does not make use of DAOs (obviously). - For CMP the data access components are generated at deployment time by the container tools. An entity bean using CMP must not have explicit data access. The Bean Provider is responsible for using the cmp-field elements of the deployment descriptor to declare the instance’s fields that the container must load and store at defined times. The fields must be defined in the entity bean class as public and must not be defined as transient. - The types that can be assigned to a container-managed field are: Java primitives, Java serializable types, and references of EJBs remote or home interfaces. - CMP has the following limitations: - Data Aliasing: An update of a data item done through a container-managed field of one entity bean may not be visible to another entity bean in the same transaction if the other entity bean maps to the same data item. - Eager Loading of State: The container loads the entire object state into the container-managed fields before invoking the ejbLoad method. - An entity bean instance is always in one of the following three states: - Does not exist: No instance of the bean exists. - Pooled: An instance in pooled state is not associated with any particular entity object identity. Until it is requested, the bean instance remains inactive unless it is used to service a find request. Bean instances in the Pooled state typically service find requests since they aren’t busy and find methods do not depend on the instance’s state. - Ready: An instance in the ready state is assigned an entity object identity. A bean enters the Ready state via calls to ejbCreate/ejbPostCreate or ejbActivate. Once in the ready state the container can call ejbLoad or ejbStore on the bean zero or more times. - Each entity bean has its own pool of instances. All instances in the pool are considered equivalent, and therefore any instance can be assigned by the container to any entity object identity at the transition to the ready state. The instance does not move to the ready state during the execution of a finder method. - The container can passivate an entity bean instance within a transaction. Passivating an entity bean causes the ejbStore method to be invoked and the ejbPassivate method returns the instance to the pooled state. - When a find method is executed, each bean found will be realized by transitioning an instance from the Pooled state to the Ready state. - A RuntimeException thrown from any method of the entity bean class results in the transition to the "does not exist" state. - From the client perspective, the corresponding entity object continues to exist. The client can continue accessing the entity object through its remote interface because the container can use a different instance to delegate the client’s requests. The container is not required to maintain a pool of instances in the pooled state. The pooling approach is an example of a possible implementation, but it is not required. - An instance of an entity bean with BMP can cache the entity object’s state between business method invocations. An instance may choose to cache the entire entity object’s state, part of the state, or no state at all. - When the container invokes ejbStore the instance must push all cached updates of the entity’s state to the database. - When the container invokes ejbLoad the instance must discard any cached entity object’s state. The instance may, but is not required to, refresh the cached state by reloading it from the database. - The use of the ejbLoad and ejbStore methods for caching an entity object’s state in the instance works well only if the container can use transaction boundaries to drive the methods. Therefore, these methods are unreliable if the transaction attribute is set to Not Supported for the method or the bean. - The container will ensure appropriate synchronization for entity objects that are accessed concurrently from multiple transactions. - If an instance of a non-reentrant entity bean executes a client request in a given transaction context and another request with the same transaction context arrives for the same entity object, the container will throw a RemoteException to the second client. This allows a bean to be written as single-threaded and non-reentrant. It is not recommended to write reentrant entity beans. ** Deployment Descriptor - Deployment descriptors contain the following kinds of information: - EJB name - Class names of the home if, remote if, and the bean - Primary key class name - Persistence type (BMP vs CMP) - Reentrant - Field names of CMP fields - Environmental or property entries - References to other beans (using the home & remote if names) - References to external resources like database connections - Security roles for accessing the bean/bean methods - Method permissions that map security roles to the methods they may invoke - Transactional attributes of the beans methods - In container-transaction elements specific method declarations override more general declarations. - The following methods must be assigned tx attributes for each bean in the DD: - For Entity: - All business methods in the remote if (and superinterfaces) - Create methods in the home if - Find methods in the home if - Remove methods in the home (EJBHome) and remote (EJBObject) ifs - For Session: - All business methods defined in the remore if (and superinterfaces) - In EJB 1.1 the bean deployer declares the timeout in a vendor-dependent manner. Timeouts are no longer included in the deployment descriptior. - Named properties can be declared in a bean’s deployment descriptor. They can be Strings or wrapper types. ** Transaction Management - Dirty Read: A dirty read occurs when the first transaction reads uncommitted changes made by a second transaction. If the second transaction is rolled back, the data read by the first transaction becomes invalid because the rollback undoes the changes. - Repeatable Read: A repeatable read is when the data read is guaranteed to look the same if read again during the same transaction. - Phantom Read: Phantom reads occur when new records added to the database are detectable by transactions that started prior to the insert. Queries will include records added by other transactions after their transaction has started. - Isolation levels are commonly used in database systems to describe how locking is applied to data within a transaction. - 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. Dirty reads are prevented; nonrepeatable reads and phantom reads can occur. Bean methods with this isolation level cannot read uncommitted data. - Repeatable Read: The tx cannot change data that is being read by a different tx. Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean methods with this isolation level have the same restrictions as Read Committed and can only execute - Serializable: The transaction has exclusive read and update privileges to data; different transactions can neither read nor write the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. Most restrictive isolation level. - In EJB 1.1 isolation levels are not controlled through declarative attributes as was the case in EJB 1.0. In EJB 1.1, the deployer sets transaction isolation levels if the container manages the transaction. The bean developer sets the transaction isolation level if the bean manages the transaction. - As the isolation levels become more restrictive the performance of the system decreases because more restrictive isolation levels prevent transactions from accessing the same data. - Different EJB servers allow different levels of granularity for setting isolation levels; some servers defer this responsibility to the database. In some servers, you may be able to set different isolation levels for different methods, while other products may require the same isolation level for all methods in a bean, or possibly even all beans in the container. - Bean managed txs in stateful session beans, however, allow the bean developer to specify the transaction isolation level using the API of the resource providing persistent storage. - For stateless session beans transactions that are managed using the UserTransaction must be started and completed within the same method. - For stateful session beans a tx can begin in one method and be committed in another because a stateful session bean is only used by one client. ** General - The remote interface for an enterprise bean defines the bean’s business methods. It also has a method for removing the bean. - The home interface defines the bean’s life cycle methods (creating, removing, finding). Find methods are only used by entity beans. - The bean class actually implements the bean’s business methods. - The primary key is a simple class that provides a pointer into the database and is only needed by entity beans. - The bean class must define a default constructor. - The bean class must not define the finalize method. - The ejbCreate method for an entity bean using BMP returns a PK instance. - The ejbCreate method for a CMP entity bean returns a null for the PK instance. - The ejbCreate method for a session bean returns void. - EJB 1.1 doesn’t use the JARs manifest. The first thing reading the JAR is the deployment descriptor. EJB 1.1 deployment descriptors are implemented in XML. - Having a client interact directly with entity beans is a common but bad design approach. Using a session bean between a client and an entity bean is a better approach. Session beans, if used properly, can substantially reduce network traffic by limiting the number of requests over the network to perform a task. Session beans can also reduce the number of network connections needed by the client. - Conceptually, an EJB server may have many containers, each of which may contain one or more types of enterprise beans. - EJB, by default, prohibits concurrent access to bean instances. In other words, several clients can be connected to one EJB object, but only one client thread can access the bean instance at a time. - The EJB specification prohibits use of the synchronized keyword. - EJB prohibits beans from creating their own threads. - In EJB 1.1 all beans have a default JNDI context called the environment naming context (ENC). The default context exists in the namespace (directory) called "java:comp/env" and its subdirectories. When a bean is deployed any beans it uses are mapped into the directory "java:comp/env/ejb" so that the bean references can be obtained at runtime through a simple and consistent use of the JNDI ENC. This eliminates network and implementation specific use of JNDI to obtain bean references. - EJB 1.1 provides a new object called a HomeHandle. The HomeHandle can be obtained from EJBObject. It allows a remote home reference to be stored and used later. - There is also a Handle object. A Handle is a serializable reference to the EJB object. A Handle allows an EJB object remote reference that points to the same type of session bean or the same unique entity bean that the handle came from to be recreated. It might appear that Handle and the primary key do the same thing but they are different. Using the primary key requires you to have the correct EJB home. If you no longer have a reference to the EJB home you must use JNDI to get a new home. The Handle object is easier to use because it encapsulates the details of doing a JNDI lookup on the container. With the Handle the correct EJB object can be obtained in one method call rather than three. A handle can be used with either type of EJB. A handle allows you to work with a stateful session bean, deactivate the bean, and then reactivate it later using the handle. The Handle is less stable than the PK because it relies on the networking configuration and naming to remain stable. - Java RMI requires that all parameters and return values be either Java primitive types or objects that implement the Serializable interface. Serializable objects are passed by copy (passed by value). ** EJB-CORBA - There is a standard mapping of the EJB architecture client-view contract to the CORBA protocols. The EJB-to-CORBA mapping not only enables on-the-wire interoperability among different impls of the EJB container but also allows non-Java clients to access EJBs through standard CORBA APIs. ****************************************** ****************************************** ****************************************** ************ EJB 2.0 ********************* ****************************************** ****************************************** ****************************************** ** Books: - EJB - Monson Haefel ** EJB 2.0 - Supports asynchronous messaging - RemoteHome interface defines the bean's lifecycle methods, that can be accessed by apps outside the EJB container. - LocalInterface for an EJB defines the bean's business methods, that can be used by other beans co-located in the same container. It allows beans to interact without the overhead of a distributed object protocol. - LocalHomeInterface: defines the bean's life cycle methods that can be used by other beans co-located in the same container. - CMP beans are declared as abstract with abstract accessor methods - defines the DTD and EJB session in the deployment descriptor. - EJB object has a corresponding EjbLocalObject. ** Message driven beans (MDB) - ~ can receive and send asynchronous JMS messages, and can also interact with RMI components. ~ acts as an integration point for an EJB app, allowing other apps to send asynchronous messages: useful for integration with legacy systems. - ~ does not have a component interface, but it may become a client to another session or entity bean and interact with those beans thru their component interfaces. - Remote, local and home interfaces are not defined. ~ would define only a few callback methods and no business methods. OnMessage() is reqd. to be defined. - ~ are not persistent: implements javax.ejb.MessageDrivenBean - In many ways, ~ fulfills the same role as session bean by managing the work flow of entity and session bean to complete a given task. - Java apps or legacy system that need to access EJB apps can send messages via JMS to ~