Skip Headers
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 3 (10.1.3)
B14428-02
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
 
Next
Next
 

1 Understanding Enterprise JavaBeans

The Java 2 Enterprise Edition(J2EE) Enterprise JavaBeans (EJB) are a component architecture that you use to develop and deploy object-oriented, distributed, enterprise-scale applications. An application written according to the Enterprise JavaBeans architecture is scalable, transactional, and secure. The component types that you can create are commonly referred to as Enterprise JavaBeans.

This chapter describes the following:

What are Enterprise JavaBeans?

The EJB architecture is flexible enough to implement the objects that Table 1-1 lists.

Table 1-1 EJB Types

Type Description See ...

Session

An EJB 3.0 or EJB 2.1 EJB component created by a client for the duration of a single client/server session used to perform operations for the client.

"What is a Session Bean?"


    Stateless

A session bean that does not maintain conversational state. Used for reusable business services that are not connected to any specific client.

"What is a Stateless Session Bean?"


    Stateful

A session bean that does maintain conversational state. Used for conversational sessions with a single client (for the duration of its lifetime) that maintain state, such as instance variable values or transactional state.

"What is a Stateful Session Bean?"


Entity

An EJB 3.0 compliant light-weight entity object that represents persistent data stored in a relational database using container-managed persistence. Because it is not a remotely accessible component, an entity can represent a fine-grained persistent object.

"What is an EJB 3.0 Entity?"


Entity Bean

An EJB 2.1 EJB component that represents persistent data stored in a relational database.

"What is an EJB 2.1 Entity Bean?"


    CMP

A Container-Managed Persistence (CMP) entity bean is an entity bean that delegates persistence management to the container that hosts it.

"What is an EJB 2.1 CMP Entity Bean?"


    BMP

A Bean-Managed Persistence (BMP) entity bean is an entity bean that manages its own persistence.

"What is an EJB 2.1 BMP Entity Bean?"


MDB

A Message-Driven Bean (MDB) is an EJB 3.0 or EJB 2.1 EJB component that functions as an asynchronous consumer of Java Message Service (JMS) messages.

"What is a Message-Driven Bean?"



For more information, see:

What is the Anatomy of an EJB 3.0 EJB?

Using EJB 3.0, the interfaces for your EJB implementation are not restricted by EJB type. For example, in your EJB 3.0 entity bean implementation, you may implement an EJB using a plain old Java object (POJO) and any plain old Java interfaces (POJI): you do not need to implement interfaces like javax.ejb.EntityBean and you do not need to provide separate interfaces that extend EJBHome, EJBLocalHome, EJBObject, or EJBLocalObject. A client may instantiate an EJB 3.0 POJO entity instance with new (or the EntityManager: see "How Do You Query for an EJB 3.0 Entity?"). A client may instantiate an EJB 3.0 session bean using dependency injection or JNDI lookup. For more information, see, "EJB 3.0 Support".

Table 1-2 lists the parts you create when developing an EJB 3.0 EJB.

Table 1-2 Parts of an EJB 3.0 EJB

Part Type Description

Home interface

POJI

An optional POJI annotated with @Home that specifies an object that the container itself implements: the home object. The @Home is only provided to help EJB 3.0 beans interoperate with EJB 2.1 clients, if necessary. Most EJB 3.0 bean instances will not need to provide a home interface.

Component interface

POJI

An mandatory POJI annotated with @Remote or @Local (default) that specifies the business methods that you implement in the bean and that a client can invoke. No other container service methods need be implemented unless you need to override default container behavior. The bean class does not need to implement this interface.

Bean implementation

POJO

A mandatory POJO that may optionally implement a component interface and contains the Java code that implements the methods defined in the optional home interface and component interface (business methods). If necessary, you can optionally annotate any method to serve as a container lifecycle callback function.

Deployment descriptor

ejb-jar.xml

orion-ejb-jar.xml

toplink-ejb-jar.xml

ejb3-toplink-sessions.xml

persistence.xml

Optional means of specifying attributes of the bean for deployment. These designate configuration specifics, such as environment, interface names, transactional support, type of EJB, and persistence information. Because this metadata can be expressed entirely through annotations (or defaults), deployment descriptor XML files are less important in EJB 3.0. Configuration in a deployment descriptor XML file overrides the corresponding annotation configuration, if present. For more information, see "Understanding EJB Deployment Descriptor Files".


As Figure 1-1 illustrates, to acquire an EJB 3.0 EJB instance, a Web client (such as a servlet) or Java client uses JNDI while an EJB client may use either JNDI or resource injection. For more information about EJB clients, see "What Type of Client Do You Have?".

For entity beans, EJB 3.0 provides an EntityManager that you use to create, find, merge, and persist an EJB 3.0 entity (see "How Do You Query for an EJB 3.0 Entity?").

Figure 1-1 A Client Using an EJB 3.0 Stateful Session Bean by Component Interface

The events that occur in a stateless session bean
Description of "Figure 1-1 A Client Using an EJB 3.0 Stateful Session Bean by Component Interface"

The client in Figure 1-1 accesses the EJB as follows:

  1. The client retrieves the component interface of the bean.

    The servlet or Java client uses JNDI to look up an instance of Cart.

    The EJB client uses resource injection by annotating a Cart instance variable with the @EJB annotation: at run time, the EJB container will ensure that the variable is initialized accordingly.

    In both cases, the EJB container manages instantiation. A home interface is not necessary.

  2. The client invokes a method defined in the component interface (remote or local interface), which delegates the method call to the corresponding method in the bean instance (through a stub).

  3. The client can destroy the stateful session bean instance by invoking a method in its component interface that is annotated in the bean instance with @Remove.

    Stateless session beans do not require a remove method; the container removes the bean if necessary. The container can also remove stateful session beans that exceed their configured timeout or to maintain the maximum configured pool size. Entity beans do not require a remove method; you use the EJB 3.0 EntityManager to create and destroy entity beans.

What is the Anatomy of an EJB 2.1 EJB?

Using EJB 2.1, the interfaces for your EJB implementation are based on EJB type. For example, in your EJB 2.1 entity bean implementation, you must implement the javax.ejb.EntityBean interface and you must provide separate interfaces that extend EJBHome or EJBLocalHome and EJBObject or EJBLocalObject. A client may instantiate an EJB 2.1 EJB instance only with a create method that your EJB home interface provides. For more information, see "EJB 2.1 Support".

Table 1-3 lists the parts you create when developing an EJB 2.1 EJB.

Table 1-3 Parts of an EJB 2.1 EJB

Part Type Description

Home interface

javax.ejb.EJBHome (remote)

javax.ejb.EJBLocalHome

Specifies the interface to an object that the container itself implements: the home object. The home interface contains the life cycle methods, such as the create methods that specify how a bean is created.

Component interface

javax.ejb.EJBObject (remote)

javax.ejb.EJBLocalObject

Specifies the business methods that you implement in the bean. The bean must also implement additional container service methods. The EJB container invokes these methods at different times in the life cycle of a bean.

Bean implementation

javax.ejb.SessionBean

javax.ejb.EntityBean

javax.ejb.MessageDrivenBean

Contains the Java code that implements the methods defined in the home interface (life cycle methods), component interface (business methods), and the required container methods (container callback functions).

Deployment descriptor

ejb-jar.xml

toplink-ejb-jar.xml

orion-ejb-jar.xml

Specifies attributes of the bean for deployment. These designate configuration specifics, such as environment, interface names, transactional support, type of EJB, and persistence information.


A client uses the home interface to acquire an EJB 2.1 EJB instance and uses the component interface to invoke its business methods as Figure 1-2 illustrates. For more information about EJB clients, see "What Type of Client Do You Have?".

Figure 1-2 A Client Using an EJB 2.1 Stateless Session Bean by Home and Component Interface

The events that occur in a stateless session bean
Description of "Figure 1-2 A Client Using an EJB 2.1 Stateless Session Bean by Home and Component Interface"

The client in Figure 1-2 accesses the EJB as follows:

  1. The client retrieves the home interface of the bean—normally through JNDI.

  2. The client invokes the create method on the home interface reference (home object). This creates the bean instance and returns a reference to the component interface (remote or local interface) of the bean.

  3. The client invokes a method defined in the component interface (remote or local interface), which delegates the method call to the corresponding method in the bean instance (through a stub).

  4. The client can destroy the bean instance by invoking the remove method that is defined in the component interface (remote or local interface).

    For some beans, such as stateless session beans, calling the remove method does nothing: in this case, the container is responsible for removing the bean instance.

What is the Lifecycle of an EJB?

The lifecycle of an EJB involves important events such as creation, passivation, activation, and removal. Each such event is associated with a callback defined on the EJB class (see "Callback Methods"). The container invokes the callback prior to or immediately after the lifecycle event (depending on the event type).

The lifecycle events associated with an EJB and whether or not the container or the bean provider is responsible for implementing callbacks is determined by the type of EJB you are developing (as specified in the appropriate EJB interface).

For an EJB 3.0 bean, when the container is responsible for the lifecycle callback, you do not need to provide an implementation in your bean unless you want to perform some additional logic.

For an EJB 2.1 bean, even when the container is responsible for the lifecycle callback, and even if you do not want to perform additional logic, you must at least provide an empty implementation of the lifecycle methods to satisfy the requirements of the applicable EJB interface.

For more information, see:

Callback Methods

A lifecycle callback method is a method of an EJB class that you define to handle a lifecycle event (see "What is the Lifecycle of an EJB?"). The container invokes the callback associated with a given lifecycle event immediately prior to or immediately after the lifecycle event (depending on the event type).

You implement a lifecycle callback method to change the default behavior of an EJB.

For an EJB 3.0 bean, you can annotate any EJB class method as a lifecycle method.

For an EJB 2.1 bean, you must at least provide an empty implementation of the lifecycle methods to satisfy the requirements of the applicable EJB interface.

What is EJB Context?

The EJBContext interface provides an instance with access to the container-provided runtime context of an EJB 2.1 EJB bean instance. This interface is extended by the SessionContext, EntityContext, and MessageDrivenContext interfaces to provide additional methods specific to the enterprise interface Bean type.

The javax.ejb.EJBContext interface has the following definition:

public interface EJBContext {
    public EJBHome         getEJBHome(); 
    public Properties      getEnvironment();
    public Principal       getCallerPrincipal();
    public boolean         isCallerInRole(String roleName);
    public UserTransaction getUserTransaction();
    public boolean         getRollbackOnly();
    public void            setRollbackOnly();
}

A bean needs the EJB context when it wants to perform the operations listed in Table 1-4.

Table 1-4 EJB 2.1 EJBContext Operations

Method Description

getEnvironment

Get the values of properties for the bean.

getUserTransaction

Get a transaction context, which enables programmatic transaction demarcation when using bean managed transactions (BMT). This is valid only for beans that have been designated transactional.

setRollbackOnly

Set the current transaction so that it cannot be committed. Applicable only to container-managed transactions.

getRollbackOnly

Check whether the current transaction is marked for rollback only. Applicable only to container-managed transactions.

getEJBHome

Retrieve the object reference to the corresponding EJBHome (home interface) of the bean.

lookup

Use JNDI to retrieve the bean by environment reference name. When using this method, you do not prefix the bean reference with "java:comp/env".


Do not confuse EJBContext with IntialContext (see "Configuring the Initial Context Factory").

For more information, see:

How Do Annotations and Resource Injection Work?

Using the @Resource or @EJB annotation, an EJB 3.0 bean may use dependency injection mechanisms to acquire references to resources or other objects in its environment. You use @Resource to inject non-EJB resources and @EJB to inject EJBs.

If an EJB 3.0 bean makes use of dependency injection, OC4J injects these references after the bean instance is created, and before any business methods are invoked.

If a dependency on the EJB context is declared, the EJB context is also injected (see "What is EJB Context?").

If dependency injection fails, OC4J discards the bean instance.


Note:

In this release, OC4J does not support resource injection in the Web container. For more information, see "Servlet or JSP Client").

Annotations are another way of specifying an environment reference without having to use XML. When you annotate a field or property, the container injects the value into the bean on your behalf by looking it up from JNDI. When a reference is specified using annotations, you can still look it up normally using JNDI.

Example 1-1 shows how annotations relate to JNDI. The annotations in this example correspond to the ejb-jar.xml file equivalent in Example 1-2. Your code would have the exact same behavior if this XML and JNDI was used instead.

Example 1-1 Using Annotations and Resource Injection

@Stateless
@EJB(name="bean1", businessInterface=Bean1.class)
public class MyBean 
{
    @EJB Bean2 bean2;

    public void doSomething()
    {
        // Bean2 is already injected and available
        bean2.foo();
        // or it can be looked up from JNDI
        ((Bean2)(new InitialContext().lookup("java:comp/env/bean2"))).foo();
        // Bean1 has not been injected and is only available through JNDI
        ((Bean1)(new InitialContext().lookup("java:comp/env/bean1"))).foo();
    }
}

Example 1-2 Equivalent ejb-jar.xml File Configuration

<ejb-local-ref>
    <ejb-ref-name>bean1</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>Bean1.class</local>
</ejb-local-ref>

<ejb-local-ref>
    <ejb-ref-name>bean2</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>Bean2.class</local>
    <injection-target>
        <injection-target-name>bean2</injection-target-name>
    </injection-target>
</ejb-local-ref>

What is a Session Bean?

A session bean is an EJB 3.0 or EJB 2.1 EJB component created by a client for the duration of a single client/server session. A session bean performs operations for the client. Although a session bean can be transactional, it is not recoverable should a system failure occur. Session bean objects are either stateless (see "What is a Stateless Session Bean?") or stateful: maintaining conversational state across method calls and transactions (see "What is a Stateful Session Bean?"). If a session bean maintains state, then OC4J manages this state if the object must be removed from memory ("When Does Stateful Session Bean Passivation Occur?"). However, the session bean object itself must manage its own persistent data.

From a client's perspective, a session bean is a non-persistent object that implements some business logic running on the application server. For example, in an on-line store application, you can use a session bean to implement a ShoppingCartBean that provides a Cart interface that the client uses to invoke methods like purchaseItem and checkout.

Each client is allocated its own session object. A client does not directly access instances of the session bean's class: a client accesses a session object through the session bean's home ("Implementing the Home Interfaces") and component ("Implementing the Component Interfaces") interfaces. The client of a session bean may be a local client, a remote client, or a Web service client (stateless session bean only), depending on the interface provided by the bean and used by the client.

OC4J maintains a session context for each session bean instance (see "What is Session Context?") that you use to make callback requests to the container.

This section describes:

For more information, see:

What is a Stateless Session Bean?

A stateless session bean is a session bean with no conversational state. All instances of a particular stateless session bean class are identical.

A stateless session bean and its client do not share state or identity between method invocations. A stateless session bean is strictly a single invocation bean. It is employed for reusable business services that are not connected to any specific client, such as generic currency calculations, mortgage rate calculations, and so on. Stateless session beans may contain client-independent, read-only state across a call. Subsequent calls are handled by other stateless session beans in the pool. The information is used only for the single invocation.

OC4J maintains a pool of these stateless beans to service multiple clients. An instance is taken out of the pool when a client sends a request. There is no need to initialize the bean with any information.

The client of a stateless session bean may be a Web service client. Only a stateless session bean may provide a Web service client view.

For more information, see:

What is the Stateless Session Bean Lifecycle?

The lifecycle for EJB 3.0 (see Table 1-5) and EBJ 2.1 (see Table 1-6) stateless session beans are identical. The difference is in how you register lifecycle callback methods.

Table 1-5 lists the optional EJB 3.0 stateless session bean lifecycle callback methods you can define using annotations. For EJB 3.0 stateless session beans, you do not need to implement these methods.

Table 1-5 Lifecycle Methods for an EJB 3.0 Stateless Session Bean

Annotation Description

@PostConstruct

This optional method is invoked for a stateful session bean before the first business method invocation on the bean. This is at a point after which any dependency injection has been performed by the container.

@PreDestroy

This optional method is invoked for a stateful session bean when the instance is in the process of being removed by the container. The instance typically releases any resources that it has been holding.


Table 1-6 lists the EJB 2.1 lifecycle methods, as specified in the javax.ejb.SessionBean interface, that a stateful session bean must implement. For EJB 2.1 stateful session beans, you must at the least provide an empty implementation for all callback methods.

Table 1-6 Lifecycle Methods for an EJB 2.1 Stateless Session Bean

EJB Method Description

ejbCreate

The container invokes this method right before it creates the bean. Use this method to initialize non-client specific information such as retrieving a data source.

ejbActivate

This method is never called for a stateless session bean. Provide an empty implementation only.

ejbPassivate

This method is never called for a stateless session bean. Provide an empty implementation only.

ejbRemove

The container invokes this method before it ends the life of the stateless session bean. Use this method to perform any required clean-up—for example, closing external resources such as a data source.

setSessionContext

The container invokes this method after it first instantiates the bean. Use this method to obtain a reference to the context of the bean. For more information, see "Implementing the setSessionContext Method".


For more information, see:

What is a Stateful Session Bean?

A stateful session bean is a session bean that maintains conversational state.

Stateful session beans are useful for conversational sessions, in which it is necessary to maintain state, such as instance variable values or transactional state, between method invocations. These session beans are mapped to a single client for the life of that client.

A stateful session bean maintains its state between method calls. Thus, there is one instance of a stateful session bean created for each client. Each stateful session bean contains an identity and a one-to-one mapping with an individual client.

When the container determines that it must remove a stateful session bean from memory (to free up resources), the container maintains its state by passivation: serializing the bean to disk. This is why the state that you passivate must be serializable. However, this information does not survive system failures. When the bean instance is requested again by its client, the container activates the previously passivated bean instance.

The type of state that is saved does not include resources. The container invokes the ejbPassivate method within the bean to provide the bean with a chance to clean up its resources, such as sockets held, database connections, and hash tables with static information. All these resources can be reallocated and re-created during the ejbActivate method.


Note:

You can turn off passivation for stateful session beans (see "Configuring Passivation").

If the bean instance fails, the state can be lost—unless you take action within your bean to continually save state. However, if you must make sure that state is persistently saved in the case of failovers, you may want to use an entity bean for your implementation. Alternatively, you could also use the SessionSynchronization interface to persist the state transactionally.

For example, a stateful session bean could implement the server side of a shopping cart on-line application, which would have methods to return a list of objects that are available for purchase, put items in the customer's cart, place an order, change a customer's profile, and so on.

For more information, see

What is the Stateful Session Bean Lifecycle?

The lifecycle for EJB 3.0 (see Table 1-7) and EBJ 2.1 (see Table 1-8) stateful session beans are identical. The difference is in how you register lifecycle callback methods.

Table 1-7 lists the optional EJB 3.0 stateful session bean lifecycle callback methods you can define using annotations. For EJB 3.0 stateful session beans, you do not need to implement these methods.

Table 1-7 Lifecycle Methods for an EJB 3.0 Stateful Session Bean

Annotation Description

@PostConstruct

This optional method is invoked for a stateful session bean before the first business method invocation on the bean. This is at a point after which any dependency injection has been performed by the container.

@PreDestroy

This optional method is invoked for a stateful session bean when the instance is in the process of being removed by the container. The instance typically releases any resources that it has been holding.

@PrePassivate

The container invokes this method right before it passivates a stateful session bean. For more information, see:

@PostActivate

The container invokes this method right after it reactivates a formerly passivated stateful session bean.


Table 1-8 lists the EJB 2.1 lifecycle methods, as specified in the javax.ejb.SessionBean interface, that a stateful session bean must implement. For EJB 2.1 stateful session beans, you must at the least provide an empty implementation for all callback methods.

Table 1-8 Lifecycle Methods for an EJB 2.1 Stateful Session Bean

EJB Method Description

ejbCreate

The container invokes this method right before it creates the bean. Stateless session beans must do nothing in this method. Stateful session beans can initiate state in this method.

ejbActivate

The container invokes this method right after it reactivates the bean.

ejbPassivate

The container invokes this method right before it passivates the bean. For more information, see:

ejbRemove

A container invokes this method before it ends the life of the session object. This method performs any required clean-up—for example, closing external resources such as file handles.

setSessionContext

The container invokes this method after it first instantiates the bean. Use this method to obtain a reference to the context of the bean. For more information, see "Implementing the setSessionContext Method".


For more information, see:

When Does Stateful Session Bean Passivation Occur?

Passivation enables the container to preserve the conversational state of an inactive idle bean instance by serializing the bean and its state into a secondary storage and removing it from memory. Before passivation, the container invokes the PrePassivate or ejbPassivate method enabling the bean developer to clean up held resources, such as database connections, TCP/IP sockets, or any resources that cannot be transparently passivated using object serialization. Only certain object types can be serialized and passivated (see "What Object Types Can Be Passivated?").

Passivation is enabled by default. For more information on enabling and disabling passivation, see "Configuring Passivation".

OC4J will passivate stateful session beans when any combination of the following criteria is met:

  • exceed idle timeout

  • exceed threshold for maximum number of instances or exceed absolute maximum number of instances

  • exceed threshold for maximum JVM memory consumption

  • shutdown OC4J instance

Passivation of beans is performed using the least recently used algorithm: of the beans eligible for passivation, OC4J passivates the least used first.

In addition, you can specify how frequently OC4J checks this criteria and the number of instances to passivate when the criteria is met.

For information on configuring this criteria, see "Configuring Passivation Criteria".

If the passivation serialization fails, then the container attempts to recover the bean back to memory as if nothing happened. No future passivation attempts will occur for any beans that fail passivation. Also, if activation fails, the bean and its references are completely removed from the container.

When a client invokes one of the methods of the passivated bean instance, the preserved conversational state data is activated, by de-serializing the bean from secondary storage, and brought back into memory. Before activation, the container invokes the ejbActivate method so that the bean developer can restore the resources released during ejbPassivate. For more information on passivation, see the EJB specification.

A stateful session bean can passivate only certain object types, as designated in "What Object Types Can Be Passivated?". If you do not prepare your stateful session beans for passivation by releasing all resources and only allowing state to exist within the allowed object types, then passivation will always fail.

If new bean data is propagated to a passivated bean in a cluster, then the bean instance data is overwritten by the propagated data.

What Object Types Can Be Passivated?

When a stateful session bean is passivated, it is serialized to secondary storage. To be successful, the conversational state of a bean must consist of only primitive values and the following data types:

  • serializable object (note that you do not necessarily need to declare the field type as serializble as long as the field is initialized with a subclass of the field type that is serializable)

  • null

  • reference to an EJB business interface

  • reference to an EJB remote interface, even if the stub class is not serializable

  • reference to an EJB remote home interface, even if the stub class is not serializable

  • reference to an EJB local interface, even if it is not serializable

  • reference to an EJB local home interface, even if it is not serializable

  • reference to the SessionContext object, even if it is not serializable

  • reference to the environment naming context (that is, the java:comp/env JNDI context) or any of its subcontexts

  • reference to the UserTransaction interface

  • reference to resource manager connection factory

  • reference to an EntityManager object, even if it is not serializable

  • reference to an EntityManagerFactory object, even if it is not serializable

  • reference to javax.ejb.Timer object

  • An object that is not directly serializable, but becomes serializable by replacing a reference to an EJB business interface, an EJB home and component interface, the reference to the SessionContext object, the reference to the java:comp/env JNDI context and its subcontexts, the reference to the UserTransaction interface, and the reference to the EntityManager, EntityManagerFactory, or both by serializable objects during the object's serialization.

You are responsible for ensuring that all non-transient fields are of these types after the PrePassivate method (see "Configuring a Lifecycle Callback Method for an EJB 3.0 Session Bean") or ejbPassivate method (see "Configuring a Lifecycle Callback Method for an EJB 2.1 Session Bean") completes. Within this method, you must set all transient or non-serializable fields to null.

Where is a Passivated Stateful Session Bean Stored?

By default, when OC4J passivates a stateful session bean, it writes the serialized instance to <OC4J_HOME>\j2ee\home\persistence.

Passivation uses space within this directory to store the passivated beans. If passivation allocates large amounts of disk space, you may need to change the directory to a place on your system where you have the space available (see "Configuring Passivation Location").

What is Session Context?

OC4J maintains a javax.ejb.SessionContext for each session bean instance and makes this session context available to the beans. The bean may use the methods in the session context to make callback requests to the container.

In addition, you can use the methods inherited from EJBContext (see "What is EJB Context?").

For more information, see:

OC4J initializes the session context after it first instantiates the bean. It is the bean provider's responsibility to enable the bean to retrieve the session context. The container will never call this method from within a transaction context. If the bean does not save the session context at this point, the bean will never gain access to the session context.

When the container calls this method, it passes the reference of the SessionContext object to the bean. The bean can then store the reference for later use.

If the session bean instance stores in its conversational state an object reference to the SessionContext (either with a setSessionContext method or using resource injection), OC4J can save and restore the reference across the instance's passivation. OC4J can replace the original SessionContext object with a different and functionally equivalent SessionContext object during activation.

What is an EJB 3.0 Entity?

An EJB 3.0 entity is an EJB 3.0 compliant light-weight entity object that manages persistent data, performs complex business logic, potentially uses several dependent Java objects, and can be uniquely identified by a primary key.

EJB 3.0 entities represent persistent data stored in a relational database automatically using container-managed persistence.

EJB 3.0 entities are persistent because their data is stored persistently in some form of data storage system, such as a database: they do survive a server failure, failover, or a network failure. When an entity is re-instantiated, the state of the previous instance is automatically restored.

An entity models a business entity or models multiple actions within a business process. Entity beans are often used to facilitate business services that involve data and computations on that data. For example, an application developer might implement an entity bean to retrieve and perform computation on items within a purchase order. Your entity bean can manage multiple, dependent, persistent objects in performing its tasks.

EJB 3.0 entities can represent fine-grained persistent objects because they are not remotely accessible components.

An EJB 3.0 entity can aggregate objects together and effectively persist data and related objects using container transactional, security, and concurrency services.

This section describes:

For more information, see "Implementing an EJB 3.0 Entity".

What are Container-Managed Persistence Fields?

A container-managed persistence field is a state-field that represents data that must be persisted to a database.

By specifying a CMP field, you are instructing OC4J to take responsibility for ensuring that the field's value is persisted to the database.

Using EJB 3.0, all data members are by default considered container-managed persistence fields unless annotated with @Transient.

What are Container-Managed Relationship Fields?

A container-managed relationship (CMR) field is an association-field that represents a persistent relationship to one or more other EJB 3.0 entities or EJB 2.1 CMP entity beans. For example, in an order management application the OrderEJB might be related to a collection of LineItemEJB beans and to a single CustomerEJB bean.

By specifying a CMR field, you are instructing OC4J to take responsiblity for ensuring that a reference to one or more related EJB 3.0 entities or EJB 2.1 CMP entity beans is persisted to the database. For this reason, this relationship is often referred to as a CMR or a mapping from one EJB 3.0 entity or EJB 2.1 CMP entity bean to another.

A container-managed relationship has the following characteristics:

  • Multiplicity - There are four types of multiplicities all of which are supported by Oracle Application Server:

  • Directionality - The direction of a relationship may be either bi-directional or unidirectional. In a bi-directional relationship, each entity bean has a relationship field that refers to the other bean. Through the relationship field, an entity bean's code can access its related object. If an entity bean has a relative field, then we often say that it "knows" about its related object. For example, if an ProjectEJB bean knows what TaskEJB beans it has and if each TaskEJB bean knows what ProjectEJB bean it belongs to, then they have a bi-directional relationship. In a unidirectional relationship, only one entity bean has a relationship field that refers to the other. Oracle Application Server supports both unidirectional and bi-directional relationships between EJBs.

  • EJB QL query support - EJB QL queries often navigate across relationships. The direction of a relationship determines whether a query can navigate from one bean to another. With OC4J, EJB QL queries can traverse CMP Relationships with any type of multiplicity and with both unidirectional and bi-directional relationships.

For more information, see:

What is the EJB 3.0 Entity Lifecycle?

Table 1-9 lists the optional EJB 3.0 entity lifecycle callback methods you can define using annotations. For EJB 3.0 entities, you do not need to implement these methods.

Table 1-9 Lifecycle Methods for an EJB 3.0 Entity

Annotation Description

@PrePersist

This optional method is invoked for an entity before the corresponding EntityManager persist operation is executed. This callback will be invoked on all entities to which these operations are cascaded. If this callback throws an Exception, it will cause the current transaction to be rolled back.

@PostPersist

This optional method is invoked for an entity after the corresponding EntityManager persist operation is executed. This callback will be invoked on all entities to which these operations are cascaded. This method will be invoked after the database insert operation. This may be directly after the persist operation, a flush operation, or at the end of a transaction. If this callback throws an Exception, it will cause the current transaction to be rolled back.

@PreRemove

This optional method is invoked for an entity before the corresponding EntityManager remove operation is executed. This callback will be invoked on all entities to which these operations are cascaded. If this callback throws an Exception, it will cause the current transaction to be rolled back.

@PostRemove

This optional method is invoked for an entity after the corresponding EntityManager remove operation is executed. This callback will be invoked on all entities to which these operations are cascaded. This method will be invoked after the database delete operation. This may be directly after the remove operation, a flush operation, or at the end of a transaction. If this callback throws an Exception, it will cause the current transaction to be rolled back.

@PreUpdate

This optional method is invoked before the database update operation on entity data. This may be at the time of the entity state update, a flush operation, or at the end of a transaction.

@PostUpdate

This optional method is invoked after the database update operation on entity data. This may be at the time of the entity state update, a flush operation, or at the end of a transaction.

@PostLoad

This optional method is invoked after the entity has been loaded into the current persistence context from the database or after the refresh operation has been applied to it and before a query result is returned or accessed or an association is traversed.


For more information, see "Configuring a Lifecycle Callback Method for an EJB 3.0 Entity".

What is an EJB 3.0 Entity Primary Key?

Each EJB 3.0 entity instance has a primary key that uniquely identifies it from other instances. The primary key (or the fields contained within a complex primary key) must be a container-managed persistent fields.

All fields within the primary key are restricted to::

  • primitive object types

  • serializable types

  • types that can be mapped to SQL types

In this release, you can define a primary key made up of a single, well-known serializable Java primitive or object type. The primary key variable that is declared within the bean class must be declared as public (see "Configuring an EJB 3.0 Entity Primary Key Field").

You can assign primary key values yourself, or more typically, you can create an auto-generated primary key (see "Configuring EJB 3.0 Entity Automatic Primary Key Generation").


Note:

Once the primary key for an entity bean has been set, the EJB 3.0 specification forbids you from attempting to change it. Therefore, do not expose the primary key set methods in an entity component interface.

For more information, see "Configuring an EJB 3.0 Entity Primary Key"

How Do You Query for an EJB 3.0 Entity?

In EJB 3.0, you use a javax.persistence.EntityManager to create, find, merge, and persist your EJB 3.0 entities (see "Accessing an EJB 3.0 Entity Using an EntityManager").

You can express your selection criteria using an appropriate query syntax (see "Understanding EJB Query Syntax").

Understanding EJB Query Syntax

Table 1-15 summarizes the types of query syntax you can use to define EJB queries.

Table 1-10 OC4J EJB Query Syntax Support

Query Syntax See Also

EJB QL

"Understanding EJB Query Syntax"


Native SQL

"Understanding Native SQL Query Syntax"



Oracle recommends EJB QL because it is both portable and optimizable.

Understanding EJB QL Query Syntax

EJB QL is a specification language used to define query semantics in a portable and optimizable format.

Although similar to SQL, EJB QL offers significant advantages over native SQL. While SQL applies queries against tables, using column names, EJB QL applies queries against CMP entity beans, using the abstract schema name and the CMP and CMR fields of the bean within the query. The EJB QL statement retains the object terminology. The container translates the EJB QL statement to the appropriate database SQL statement when the application is deployed. Thus, the container is responsible for converting the entity bean name, CMP field names, and CMR field names to the appropriate database tables and column names. EJB QL is portable to all databases supported by OC4J.

In EJB 3.0, EJB QL syntax includes everything in EJB 2.1 plus additional features such as bulk update and delete, JOIN operations, GROUP BY, HAVING, projection, subqueries, and the use of EJB QL in dynamic queries using the EJB 3.0 EntityManager API (see "Understanding the EJB 3.0 EntityManager Query API"). For complete details, see the EJB 3.0 persistence specification.

Oracle Application Server provides complete support for EJB QL with the following important features:

  • Automatic Code Generation: EJB QL queries are defined in the deployment descriptor of the entity bean. When the EJBs are deployed to Oracle Application Server, the container automatically translates the queries into the SQL dialect of the target data store. Because of this translation, entity beans with container-managed persistence are portable -- their code is not tied to a specific type of data store.

  • Optimized SQL Code Generation: Further, in generating the SQL code, Oracle Application Server makes several optimizations such as the use of bulk SQL, batched statement dispatch, and so on to make database access efficient.

  • Support for Oracle and Non-Oracle Databases: Further, Oracle Application Server provides the ability to execute EJB QL against any database - Oracle, MS SQL-Server, IBM DB/2, Informix, and Sybase.

  • Relationships: Oracle Application Server supports EJB QL for both single entity beans and also with entity beans that have relationships, with support for any type of multiplicity and directionality.

Using EJB 3.0, OC4J supports all of the enhanced EJB QL features defined in the EJB 3.0 persistence specification, including SQRT and date, time, and timestamp options.

Understanding Native SQL Query Syntax

In this release, the TopLink persistence manager takes the query syntax you specify (see "Understanding EJB Query Syntax") and generates Sequential Query Language (SQL) native to your underlying relational database.

EJB QL is the preferred syntax because it is portable and optimizable.

Native SQL is appropriate for taking advantage of advanced query features of your underlying relational database that EJB QL does not support.

Using EJB 3.0, you can use EntityManager method createNativeQuery(String sqlString, Class resultType) to create a native SQL query (see "Creating a Dynamic Native SQL Query with the EntityManager").


Note:

OC4J does not support EntityManager method createNativeQuery(String sqlString) nor does it support native SQL named queries (see "Implementing an EJB 3.0 Named Query" ).

To use native SQL otherwise, you must use straight JDBC calls.

Understanding the EJB 3.0 EntityManager Query API

In EJB 3.0, you can use the javax.persistence.EntityManager and javax.persistence.Query API to create and execute named queries (see "What is an EJB 3.0 Named (Predefined) Query?") or dynamic queries (see "What is an EJB 3.0 Dynamic (Ad-Hoc) Query?").

Using Query API, you can bind parameters, configure hints, and control the number of results returned.

For more information, see:

What is an EJB 3.0 Named (Predefined) Query?

A named query is the EJB 3.0 improvement of the EJB 2.1 finder method. In EJB 3.0, you can implement a named query using metadata (see "Implementing an EJB 3.0 Named Query") and then create and execute the query by name at runtime (see "Creating a Named Query with the EntityManager").

In this release OC4J supports only EJB QL named queries.

What is an EJB 3.0 Dynamic (Ad-Hoc) Query?

A dynamic query is a query that you can compose, configure, and execute at runtime. You can use dynamic queries in addition to named queries.

OC4J supports both EJB QL ("Creating a Dynamic EJB QL Query with the Entity Manager") and native SQL ("Creating a Dynamic Native SQL Query with the EntityManager") dynamic queries.

You can also create a dynamic query using the TopLink query and expression framework (see "Creating a Dynamic TopLink Expression Query with the EntityManager").

What is an EJB 2.1 Entity Bean?

An entity bean is an EJB 2.1 EJB component that manages persistent data, performs complex business logic, potentially uses several dependent Java objects, and can be uniquely identified by a primary key ("What is a CMP Entity Bean Primary Key?" or "What is a BMP Entity Bean Primary Key?").

Entity beans persist business data using one of the two following methods:

For information on choosing between CMP and BMP architectures, see "When do you use Bean-Managed versus Container-Managed Persistence?".

Entity beans are persistent because their data is stored persistently in some form of data storage system, such as a database: they do survive a server failure, failover, or a network failure. When an entity bean is re-instantiated, the state of the previous instance is automatically restored. OC4J manages this state if the entity bean must be removed from memory (see "When Does Entity Bean Passivation Occur?").

An entity bean models a business entity or models multiple actions within a business process. Entity beans are often used to facilitate business services that involve data and computations on that data. For example, an application developer might implement an entity bean to retrieve and perform computation on items within a purchase order. Your entity bean can manage multiple, dependent, persistent objects in performing its tasks.

A common design pattern pairs entity beans with a session bean that acts as the client interface. The entity bean functions as a coarse-grained object that encapsulates functionality and represents persistent data and relationships to dependent (typically find-grained) objects. Thus, you decouple the client from the data so that if the data changes, the client is not affected. For efficiency, the session bean can be collocated with entity beans and can coordinate between multiple entity beans through their local interfaces. This is known as a session facade design. See the http://java.sun.com Web site for more information on session facade design.

An entity bean can aggregate objects together and effectively persist data and related objects using container transactional, security, and concurrency services.

This section describes:

For more information, see "Implementing an EJB 2.1 Entity Bean".

What is an EJB 2.1 CMP Entity Bean?

When you choose to have the container manage your persistent data for an entity bean, you define a container-managed persistence (CMP) entity bean. A CMP entity bean class is an abstract class (the container provides the implementation class that is used at runtime) whose persistent data is specified as container-managed persistence fields (see "What are Container-Managed Persistence Fields?") for simple data or as container-managed relationship fields (see "What are Container-Managed Relationship Fields?") for relationships with other CMP entity beans. In this case, you do not have to implement some of the callback methods to manage persistence for your bean's data (see "What is the CMP Entity Bean Lifecycle?"), because the container stores and reloads your persistent data to and from the database. When you use container-managed persistence, the container invokes a persistence manager class that provides the persistence management business logic. OC4J uses the TopLink persistence manager by default. In addition, you do not have to provide management for the primary key (see "What is a CMP Entity Bean Primary Key?"): the container provides this key for the bean.

For more information, see "Implementing an EJB 2.1 CMP Entity Bean".

What are Container-Managed Persistence Fields?

A container-managed persistence field is a state-field that represents data that must be persisted to a database.

By specifying a CMP field, you are instructing OC4J to take responsibility for ensuring that the field's value is persisted to the database. All other fields in the CMP entity bean are considered non-persistent (transient).

Using EJB 2.1, you must explicitly specify CMP fields (see "Configuring an EJB 2.1 CMP Entity Bean Container-Managed Persistence Field").

What are Container-Managed Relationship Fields?

A container-managed relationship field is an association-field that represents a persistent relationship to one or more other CMP entity beans. For example, in an order management application the OrderEJB might be related to a collection of LineItemEJB beans and to a single CustomerEJB bean.

By specifying a CMR field, you are instructing OC4J to take responsiblity for ensuring that a reference to one or more related CMP entity beans is persisted to the database. For this reason, a relationship between CMP entity beans is often referred to as container-managed relationship (CMR) or a mapping from one CMP entity bean to another.

A container-managed relationship has the following characteristics:

  • Multiplicity - There are four types of multiplicities all of which are supported by Oracle Application Server:

  • Directionality - The direction of a relationship may be either bi-directional or unidirectional. In a bi-directional relationship, each entity bean has a relationship field that refers to the other bean. Through the relationship field, an entity bean's code can access its related object. If an entity bean has a relative field, then we often say that it "knows" about its related object. For example, if an ProjectEJB bean knows what TaskEJB beans it has and if each TaskEJB bean knows what ProjectEJB bean it belongs to, then they have a bi-directional relationship. In a unidirectional relationship, only one entity bean has a relationship field that refers to the other. Oracle Application Server supports both unidirectional and bi-directional relationships between EJBs.

  • EJB QL query support - EJB QL queries often navigate across relationships. The direction of a relationship determines whether a query can navigate from one bean to another. With OC4J, EJB QL queries can traverse CMP Relationships with any type of multiplicity and with both unidirectional and bi-directional relationships.

For more information, see:

What is the CMP Entity Bean Lifecycle?

Table 1-11 lists the EJB 2.1 lifecycle methods, as specified in the javax.ejb.EntityBean interface, that a CMP entity bean must implement. For EJB 2.1 CMP entity beans, you must at the least provide an empty implementation for all callback methods.

Table 1-11 Lifecycle Methods for an EJB 2.1 CMP Entity Bean

EJB Method Description

ejbCreate

You must implement an ejbCreate method corresponding to each create method declared in the home interface. When the client invokes the create method, the container first invokes the constructor to instantiate the object, then it invokes the corresponding ejbCreate method.

For a CMP entity bean, use this method to initialize container-managed persistent fields.

The return type of all ebjCreate methods is the type of the bean's primary key.

Optionally, you can initialize the bean with a unique primary key and return it. If you rely on the container to create and initialize the primary key, return null.

ejbPostCreate

The container invokes this method after the environment is set. For each ejbCreate method, an ejbPostCreate method must exist with the same arguments.

For a CMP entity bean, you can leave this implementation empty or use your implementation to initialize parameters within or from the entity context.

ejbRemove

The container invokes this method before it ends the life of the entity bean.

For a CMP entity bean, you can leave this implementation empty or use your implementation to perform any required clean-up, for example closing external resources such as file handles.

ejbStore

The container invokes this method right before a transaction commits. It saves the persistent data to an outside resource, such as a database.

For a CMP entity bean, you can leave this implementation empty.

ejbLoad

The container invokes this method when the data should be reinitialized from the database. This normally occurs after activation of an entity bean.

For a CMP entity bean, you can leave this implementation empty.

ejbActivate

The container calls this method directly before it activates an object that was previously passivated. Perform any necessary reaquisition of resources in this method.

ejbPassivate

The container calls this method before it passivates the object. Release any resources that can be easily re-created in ejbActivate, and save storage space. Normally, you want to free resources that cannot be passivated, such as sockets or database connections. Retrieve these resources in the ejbActivate method.


What is a CMP Entity Bean Primary Key?

Each entity bean instance has a primary key that uniquely identifies it from other instances. You must declare the primary key (or the fields contained within a complex primary key) as a container-managed persistent field in the deployment descriptor.

All fields within the primary key are restricted to:

  • primitive object types

  • serializable types

  • types that can be mapped to SQL types

You can define a primary key in one of the following ways:

You can assign primary key values yourself, or more typically, you can create an auto-generated primary key (see "Configuring EJB 2.1 CMP Entity Bean Automatic Primary Key Generation").


Note:

Once the primary key for an entity bean has been set, the EJB 2.1 specification forbids you from attempting to change it. Therefore, do not expose the primary key set methods in an entity bean component interface.

For more information, see "Configuring an EJB 2.1 CMP Entity Bean Primary Key".

What is an EJB 2.1 BMP Entity Bean?

When you choose to manage your persistent data for an entity bean yourself, you define a bean-managed persistence (BMP) entity bean. A BMP entity bean class is a concrete class (you provide the implementation that is used at runtime) whose persistent data is specified as bean-managed persistence fields (see "What are Bean-Managed Persistence Fields?") for simple data or as bean-managed relationship fields (see "What are Bean-Managed Relationship Fields?") for relationships with other BMP entity beans. In this case, you must implement all of the callback methods to manage persistence for your bean's data, including storing and reloading your persistent data to and from the database (see "What is the BMP Entity Bean Lifecycle?"). When you use bean-managed persistence, you must supply the code that provides the persistence management business logic. In addition, you must provide management for the primary key (see "What is a BMP Entity Bean Primary Key?").

You can specify a BMP entity bean as read-only (see "Configuring a Read-Only BMP Entity Bean") and take advantage of the optimizations that OC4J provides read-only BMP entity beans depending on the commit option you choose (see "What are Entity Bean Commit Options?")

For more information, see "Implementing an EJB 2.1 BMP Entity Bean".

What are Bean-Managed Persistence Fields?

With bean-managed persistence, the code that you write determines what BMP entity bean fields are persistent.

What are Bean-Managed Relationship Fields?

With bean-managed persistence, the code that you write implements the relationships between BMP entity beans.

What is the BMP Entity Bean Lifecycle?

Table 1-12 lists the lifecycle methods, as specified in the javax.ejb.EntityBean interface, that a BMP entity bean must implement.

For a BMP entity bean, you must provide a complete implementation of all lifecycle methods.

Table 1-12 EJB Lifecycle Methods for a BMP Entity Bean

EJB Method Description

ejbCreate

You must implement an ejbCreate method corresponding to each create method declared in the home interface. When the client invokes the create method, the container first invokes the constructor to instantiate the object, then it invokes the corresponding ejbCreate method. The ejbCreate method performs the following:

  • creates any persistent storage for its data, such as database rows

  • initializes a unique primary key and returns it

ejbPostCreate

The container invokes this method after the environment is set. For each ejbCreate method, an ejbPostCreate method must exist with the same arguments. This method can be used to initialize parameters within or from the entity context.

ejbRemove

The container invokes this method before it ends the life of the session object. This method can perform any required clean-up, for example closing external resources such as file handles.

ejbStore

The container invokes this method right before a transaction commits. It saves the persistent data to an outside resource, such as a database.

ejbLoad

The container invokes this method when the data should be reinitialized from the database. This normally occurs after activation of an entity bean.

ejbActivate

The container calls this method directly before it activates an object that was previously passivated. Perform any necessary reaquisition of resources in this method.

ejbPassivate

The container calls this method before it passivates the object. Release any resources that can be easily re-created in ejbActivate, and save storage space. Normally, you want to free resources that cannot be passivated, such as sockets or database connections. Retrieve these resources in the ejbActivate method.


For more information, see "Configuring a Lifecycle Callback Method for an EJB 2.1 BMP Entity Bean".

What is a BMP Entity Bean Primary Key?

An entity bean primary key is a uniquely identifiable value that distinguishes one instance of a particular type of entity bean class from another. Each entity bean has a persistent identity associated with it. That is, the entity bean contains a unique identity that can be retrieved if you have the primary key—given the primary key, a client can retrieve the entity bean. If the bean is not available, the container instantiates the bean and repopulates the persistent data for you.

The type for the unique key is defined by the bean provider.

All fields within the primary key are restricted to:

  • primitive object types

  • serializable types

  • types that can be mapped to SQL types

You can define a primary key in one of the following ways:

  • Define the type of the primary key as a serializable object within a <name>PK class that is serializable.

In either case, for a BMP entity bean, you create the primary key in the ejbCreate method.

What is Entity Context?

OC4J maintains a javax.ejb.EntityContext for each EJB 2.1 CMP or BMP entity bean instance and makes this entity context available to the beans. The bean may use the methods in the entity context to make callback requests to the container.

In addition, you can use the methods inherited from EJBContext (see "What is EJB Context?").

For more information, see:

How do You Avoid Database Resource Contention?

OC4J and the TopLink EJB 3.0 entity manager and EJB 2.1 persistence manager use a combination of transaction isolation (see "Transaction Isolation") and concurrency mode (see "Concurrency (Locking) Mode") to avoid database resource contention and to permit concurrent access to database tables.

Transaction Isolation

The degree to which concurrent (parallel) transactions on the same data are allowed to interact is determined by the level of transaction isolation configured. ANSI/SQL defines four levels of database transaction isolation as shown in Table 1-13. Each offers a trade-off between performance and resistance from the following unwanted actions:

  • Dirty read: a transaction reads uncommitted data written by a concurrent transaction.

  • Non repeatable read: a transaction rereads data and finds it has been modified by some other transaction that was committed after the initial read operation.

  • Phantom read: a transaction re executes a query and the returned data has changed due to some other transaction that was committed after the initial read operation.

Table 1-13 Transaction Isolation Levels

Transaction Isolation Level Dirty Read Nonrepeatable Read Phantom Read

Read Uncommitted

Yes

Yes

Yes

Read Committed

No

Yes

Yes

Repeatable Read

No

No

Yes

Serializable

No

No

No


By default, OC4J and the TopLink persistence manager provide read-committed transaction isolation.

To configure the transaction isolation mode, you must customize the TopLink EJB 3.0 entity manager (see "Customizing the TopLink Entity Manager") or EJB 2.1 persistence manager (see "Customizing the TopLink Persistence Manager").

For more information, see:

Concurrency (Locking) Mode

OC4J also provides concurrency modes for handling resource contention and parallel execution within EJB 3.0 entities and EJB 2.1 container-managed persistence (CMP) entity beans.

Bean-managed persistence entity beans manage the resource locking within the bean implementation themselves.

Concurrency modes include:

  • Optimistic Locking: Multiple users have read access to the data. When a user attempts to make a change, the application checks to ensure the data has not changed since the user read the data

    By default, the TopLink persistence manager enforces optimistic locking by using a numeric version field (also known as a write-lock field) that TopLink updates each time an object change is committed.

    TopLink caches the value of this version field as it reads an object from the data source. When the client attempts to write the object, TopLink compares the cached version value with the current version value in the data source in the following way:

    • If the values are the same, TopLink updates the version field in the object and commits the changes to the data source.

    • If the values are different, the write operation is disallowed because another client must have updated the object since this client initially read it.

  • Pessimistic Locking: The first user who accesses the data with the purpose of updating it locks the data until completing the update. This manages resource contention and does not allow parallel execution. Only one user at a time is allowed to execute the entity bean at a single time.

  • Read-only: Multiple users can execute the entity bean in parallel. The container does not allow any updates to the bean's state.

These concurrency modes are defined for each bean and apply on the transaction boundaries.

By default, OC4J and the TopLink EJB 3.0 entity manager and EJB 2.1 persistence manager use optimistic locking and all EJB 3.0 entities and CMP entity beans are not read-only.

To configure the concurrency mode, you must customize the TopLink EJB 3.0 entity manager (see "Customizing the TopLink Entity Manager") or EJB 2.1 persistence manager (see "Customizing the TopLink Persistence Manager").

For more information, see:

When Does Entity Bean Passivation Occur?

Entity bean passivation applies only to EJB 2.1 CMP entity beans.

OC4J passivates an instance when the container decides to disassociate the instance from an entity object identity, and to put the instance back into the pool of available instances. OC4J calls the instance's ejbPassivate method to give the instance the chance to release any resources (typically allocated in the ejbActivate method) that should not be held while the instance is in the pool. This method executes with an unspecified transaction context. The entity bean must not attempt to access its persistent state or relationships using the accessor methods during this method.

What are Entity Bean Commit Options?

Commit options determine entity bean instance state at transaction commit time and offer the flexibility to allow OC4J to optimize certain application conditions.

Table 1-14 lists the commit options as defined by the EJB 2.1 specification and indicates which are supported by OC4J.

Table 1-14 OC4J Support for Entity Bean Commit Options

Commit Option OC4J Support Description Instance state written to database? Instance stays ready Instance state remains valid Advantages Disadvantages

A

SupportedFoot 1 

Cached bean: At the end of the transaction, the instance stays in the ready state (cached) and the instance state is valid (ejbLoad called once on activation).

Supported
Supported
Supported

Least database access.

Exclusive access required.

Multiple threads share same bean instance (poor performance).

B

Not Supported


Stale bean: At the end of the transaction, the instance stays in the ready state (cached) but the instance state is not valid: ejbLoad and ejbStore called for each transaction.

Supported
Supported
Not Supported

Moderate database access.

Allows concurrent requests.

Overhead of multiple bean instances representing the same data.

Each transaction calls ejbLoad

C

SupportedFoot 2 

Pooled bean: At the end of the transaction, neither the instance nor its state is valid (instance will be passivated and returned to the pool). Every client call causes an ejbActivate, ejbLoad, then the business method, then ejbStore, and ejbPassivate.

Supported
Not Supported
Not Supported

Best scalability.

Allows concurrent requests.

Need not hold on to connections.

Most database access (every business method call).

No caching.


Footnote 1 BMP entity beans only (see "Commit Options and BMP Applications").

Footnote 2 CMP entity beans only (see "Commit Options and CMP Applications").

Commit Options and CMP Applications

For an EJB 2.1 CMP application deployed to OC4J using the TopLink persistence manager, by default, OC4J uses TopLink configuration to approximate commit option C. This option provides the best performance and scalability over the widest range of applications.

OC4J EJB 2.1 CMP conforms to option C in terms of lifecycle method calls. However, the TopLink persistence manager introduces the following innovations:

  • It provides caching using the TopLink cache.

  • It does not synchronize the instance with the data source at the beginning of every transaction if the instance is already in the TopLink cache.

You can use locking or synchronization with a TopLink pessimistic or optimistic locking policy to handle concurrent services to the same bean. This provides the best performance for concurrent access of the same instance while guaranteeing an instance is not updated with stale data.

For more information on making fine-grained TopLink configuration changes, see:

Commit Options and BMP Applications

For an EJB 2.1 BMP application deployed to OC4J, you can configure commit option A (see "Configuring BMP Commit Options").

When you configure a BMP entity bean as read-only, OC4J uses a special case of commit option A to improve performance. In this case, OC4J caches the instance and and does not update the instance or call ejbStore when the transaction commits. For more information, see "Configuring a Read-Only BMP Entity Bean".

You can use BMP commit option A and read-only BMP entity beans independently (that is, you can configure a BMP entity bean with commit option A without using read-only and you can use read-only without configuring a BMP entity bean with commit option A).

How Do You Query for an EJB 2.1 Entity Bean?

To query for an EJB 2.1 entity bean instance, you use a finder or select method (see "Understanding Finder Methods" and "Understanding Select Methods").

In either case, you express your selection criteria using an appropriate query syntax (see "Understanding EJB Query Syntax").

For more information, see "Using EJB 2.1 Query API".

Understanding EJB Query Syntax

Table 1-15 summarizes the types of query syntax you can use to define EJB queries.

Table 1-15 OC4J EJB Query Syntax Support

Query Syntax See Also

EJB QL

"Understanding EJB Query Syntax"


TopLink


"Understanding TopLink Query Syntax"


    Predefined Finder

"Predefined TopLink Finders"


    Default Finder

"Default TopLink Finders"


    Custom Finder

"Custom TopLink Finders"


    Custom Select

"Custom TopLink Select Methods"


Native SQL

"Understanding Native SQL Query Syntax"



Oracle recommends EJB QL because it is both portable and optimizable.

Understanding EJB QL Query Syntax

EJB QL is a specification language used to define semantics of finder and select methods (see "Understanding Finder Methods" and "Understanding Select Methods") in a portable and optimizable format. You ensure that an EJB QL statement is associated with each finder and select method.

Although similar to SQL, EJB QL offers significant advantages over native SQL. While SQL applies queries against tables, using column names, EJB QL applies queries against CMP entity beans, using the abstract schema name and the CMP and CMR fields of the bean within the query. The EJB QL statement retains the object terminology. The container translates the EJB QL statement to the appropriate database SQL statement when the application is deployed. Thus, the container is responsible for converting the entity bean name, CMP field names, and CMR field names to the appropriate database tables and column names. EJB QL is portable to all databases supported by OC4J.

In EJB 2.1, EJB QL is a subset of SQL92, that includes extensions that allow navigation over the relationships defined in an entity bean's abstract schema. The abstract schema is part of an entity bean's deployment descriptor and defines the bean's persistent fields and relationships. The term "abstract" distinguishes this schema from the physical schema of the underlying data store. The abstract schema name is referenced by EJB QL queries since the scope of an EJB QL query spans the abstract schemas of related entity beans that are packaged in the same EJB JAR file.

For an entity bean with container-managed persistence, an EJB QL query must be defined for every finder method (except findByPrimaryKey). Using OC4J with the TopLink persistence manager, you can take advantage of predefined and default finder and select methods (see "TopLink Finders" and "Custom TopLink Select Methods"). The EJB QL query determines the query that is executed by the EJB container when the finder or select method is invoked.

Oracle Application Server provides complete support for EJB QL with the following important features:

  • Automatic Code Generation: EJB QL queries are defined in the deployment descriptor of the entity bean. When the EJBs are deployed to Oracle Application Server, the container automatically translates the queries into the SQL dialect of the target data store. Because of this translation, entity beans with container-managed persistence are portable -- their code is not tied to a specific type of data store.

  • Optimized SQL Code Generation: Further, in generating the SQL code, Oracle Application Server makes several optimizations such as the use of bulk SQL, batched statement dispatch, and so on to make database access efficient.

  • Support for Oracle and Non-Oracle Databases: Further, Oracle Application Server provides the ability to execute EJB QL against any database - Oracle, MS SQL-Server, IBM DB/2, Informix, and Sybase.

  • CMP with Relationships: Oracle Application Server supports EJB QL for both single entity beans and also with entity beans that have relationships, with support for any type of multiplicity and directionality.

Using EJB 2.1, OC4J provides proprietary EJB QL extensions to support SQRT and date, time, and timestamp options not available in EJB 2.1 (see "OC4J EJB 2.1 EJB QL Extensions").

Understanding TopLink Query Syntax

In this release, because TopLink is the default persistence manager (see "TopLink Persistence Manager"), you can express selection criteria for an EJB 2.1 finder or select method using the TopLink query and expressions framework. This EJB QL alternative offers numerous advantages (see "Advantages of TopLink Queries and Expressions").

You can use the TopLink Workbench to customize your ejb-jar.xml file to create advanced finder and select methods using the TopLink query and expression framework.

You also can take advantage of the predefined and default finders and select methods that the TopLink persistence manager provides (see "TopLink Finders" and "Custom TopLink Select Methods").

For more information, see:

Advantages of TopLink Queries and Expressions

Using the TopLink expressions framework, you can specify query search criteria based on your domain object model.

Expressions offer the following advantages over SQL when you access a database:

  • Expressions are easier to maintain because, like EJB QL, the database is abstracted.

  • Changes to descriptors or database tables do not affect the querying structures in the application.

  • Expressions enhance readability by standardizing the Query interface so that it looks similar to traditional Java calling conventions. For example, the Java code required to get the street name from the Address object of the Employee class looks like this:

    emp.getAddress().getStreet().equals("Meadowlands");
    
    

    The expression to get the same information is similar:

    emp.get("address").get("street").equal("Meadowlands");
    
    
  • Expressions allow read queries to transparently query between two classes that share a relationship. If these classes are stored in multiple tables in the database, TopLink automatically generates the appropriate join statements to return information from both tables.

  • Expressions simplify complex operations. For example, the following Java code retrieves all Employees that live on "Meadowlands" whose salary is greater than 10,000:

    ExpressionBuilder emp = new ExpressionBuilder();
    Expression exp = emp.get("address").get("street").equal("Meadowlands");
    Vector employees = session.readAllObjects(Employee.class,
      exp.and(emp.get("salary").greaterThan(10000)));
    
    

    TopLink automatically generates the appropriate SQL from that code:

    SELECT t0.VERSION, t0.ADDR_ID, t0.F_NAME, t0.EMP_ID, t0.L_NAME, t0.MANAGER_ID, t0.END_DATE, t0.START_DATE, t0.GENDER, t0.START_TIME, t0.END_TIME,t0.SALARY FROM EMPLOYEE t0, ADDRESS t1 WHERE (((t1.STREET = 'Meadowlands')AND (t0.SALARY > 10000)) AND (t1.ADDRESS_ID = t0.ADDR_ID))
    
    
Understanding Native SQL Query Syntax

In this release, the TopLink persistence manager takes the query syntax you specify ("Understanding EJB QL Query Syntax" or "Understanding TopLink Query Syntax") and generates Sequential Query Language (SQL) native to your underlying relational database.

EJB QL is the preferred syntax because it is portable and optimizable.

Native SQL is appropriate for taking advantage of advanced query features of your underlying relational database that EJB QL does not support.

Using EJB 2.1 and the TopLink query syntax, you can use:

To use native SQL otherwise, you must use straight JDBC calls.

Understanding Finder Methods

A finder method is an EJB method the name of which begins with find that you define in the Home interface of an EJB (see or "Implementing the EJB 2.1 Home Interfaces") and associate with a query to return one or more instances of that EJB type. At deployment time, OC4J provides an implementation of this method that executes the associated query.

Finder methods are the means by which clients retrieve EJB 2.1 CMP entity beans. Using EJB 2.1, you can:

A finder that returns a single EJB instance has a return type of that EJB instance.

A finder that returns more than one EJB instance has a return type of Collection. If no matches are found, an empty Collection is returned. To ensure that no duplicates are returned, specify the DISTINCT keyword in the associated EJB query.

All finders throw FinderException.

At the very least, you must expose the findByPrimaryKey finder method to retrieve a reference for each entity bean using its primary key.

TopLink Finders

The TopLink persistence manager provides OC4J entity beans with a variety of predefined (see "Predefined TopLink Finders") and default (see "Default TopLink Finders") finders. You can expose these finders to your clients as you would for any other finder. You do not need to specify a corresponding query. You can also create custom TopLink finders (see "Custom TopLink Finders").

Predefined TopLink Finders

Table 1-16 lists the predefined finders you can expose for EJB 2.1 CMP entity beans. The TopLink persistence manager reserves the method names listed in Table 1-16.

Table 1-16 Predefined TopLink CMP Finders

Method Arguments Return

findAll

()

Collection

findManyByEJBQL

(String ejbql) (String ejbql, Vector args)

Collection

findManyByQuery

(DatabaseQuery query)(DatabaseQuery query, Vector args)

Collection

findManyBySQL

(String sql)(String sql, Vector args)

Collection

findByPrimaryKey

(Object primaryKeyObject)

EJBObject or EJBLocalObjectFoot 1 

findOneByEJBQL

(String ejbql)

Component interface

findOneByEJBQL

(String ejbql, Vector args)

EJBObject or EJBLocalObjectFootref 1

findOneByQuery

(DatabaseQuery query)

Component interface

findOneByQuery

(DatabaseQuery query, Vector args)

EJBObject or EJBLocalObjectFootref 1

findOneBySQL

(String sql)

Component interface

findOneBySQL

(String sql, Vector args)

EJBObject or EJBLocalObjectFootref 1


Footnote 1 Depending on whether or not the finder is defined in the home or component interface.

Example 1-4 shows an EJBHome that defines two predefined finders (findByPrimaryKey and findManyBySQL). TopLink will provide the query implementation for these finders.

Example 1-3 Specifying Predefined TopLink Finders

public interface EmpBeanHome extends EJBHome
{
    public EmpBean create(Integer empNo, String empName) throws CreateException;
 
    /**
    * Finder methods. These are implemented by the container. We can
    * customize the functionality of these methods in the deployment
    * descriptor through EJB-QL.
    **/
     
    // Predefined Finders: <query> element in ejb-jar.xml not required
 
    public Topic findByPrimaryKey(Integer key) throws FinderException;
    public Collection findManyBySQL(String sql, Vector args) throws FinderException
 
}

Default TopLink Finders

For each finder method defined in the home interface of an entity bean whose name matches findBy<CMP-FIELD-NAME> where <CMP-FIELD-NAME> is the name of a persistent field on the bean, TopLink generates a finder implementation including a TopLink query that uses the TopLink expressions framework. If the return type is a single bean type, TopLink creates a oracle.toplink.queryframework.ReadObjectQuery; if the return type is Collection, TopLink creates a oracle.toplink.queryframework.ReadAllQuery. You can expose these finders to your clients as you would for any other finder. You do not need to specify a corresponding query.

Example 1-4 shows an EJBHome that defines a default finder (findByEmpNo). TopLink will provide the query implementation for this finder.

Example 1-4 Specifying Default TopLink Finders

public interface EmpBeanHome extends EJBHome
{
    public EmpBean create(Integer empNo, String empName) throws CreateException;
 
    /**
    * Finder methods. These are implemented by the container. We can
    * customize the functionality of these methods in the deployment
    * descriptor through EJB-QL.
    **/
     
    // Default Finder: <query> element in ejb-jar.xml not required
 
    public Topic findByEmpNo(Integer empNo);
}

Custom TopLink Finders

You can take advantage of the TopLink query and expression framework to define advanced finders, including Call, DatabaseQuery, primary key, Expression, EJB QL, native SQL, and redirect finders (that delegate execution to the implementation that you define as a static method on an arbitrary helper class).

Using EJB 2.1, to create custom TopLink finders, use your existing toplink-ejb-jar.xml file with the TopLink Workbench (see "Using TopLink Workbench").

Understanding Select Methods

An entity bean select method is a query method intended for internal use within an EJB 2.1 CMP entity bean instance. You define a select method as an abstract method of the abstract entity bean class itself and associate an EJB QL query with it. You do not expose the select method to the client in the home or component interface. You may define zero or more select methods. The container is responsible for providing the implementation of the select method based on the EJB QL query you associate with it.

You typically call a select method within a business method to retrieve the value of a CMP field or entity bean references of container-managed relationship (CMR) fields. A select method executes in the transaction context determined by the transaction attribute of the invoking business method.

A select method has the following signature:

public abstract <ReturnType> ejbSelect<MethodName>(...) throws FinderException

  • It must be declared as public and abstract.

  • The return type must conform to the select method return type rules (see "What Type Can My Select Method Return?").

  • The method name must start with ejbSelect.

  • The method must throw javax.ejb.FinderException and may also throw other application-specific exceptions as well.

Although the select method is not based on the identity of the entity bean instance on which it is invoked, it can use the primary key of an entity bean as an argument. This creates a query that is logically scoped to a particular entity bean instance.

Using EJB 2.1, you can define custom EJB QL select methods (see "Implementing an EJB 2.1 EJB QL Select Method") and you can define custom TopLink select methods (see "Custom TopLink Select Methods").

What Type Can My Select Method Return?

The select method return type is not restricted to the entity bean type on which the select is invoked. Instead, it can return any type corresponding to a CMP or CMR field.

Your select method must conform to the following return type rules:

  • All values must be returned as objects; any primitive types are wrapped in their corresponding object types (for example, a primitive int is wrapped in an Integer object).

  • Single object: If your select method returns only a single item, the container returns the same type as specified in your select method signature.

    If multiple objects are returned, a FinderException is raised.

    If no objects are found, a FinderException is raised

  • Multiple objects: If your select method returns multiple items, you must define the return type as a Collection.

    Choose the Collection type to suit your needs. For example, a Collection may include duplicates, a Set eliminates duplicates, and a SortedSet will return an ordered Collection.

    If no objects are found, an empty Collection is returned.

    • CMP values: If you return multiple CMP values, the container returns a Collection of objects whose type it determines from the EJB QL select statement.

    • CMR values: If you return multiple CMR values, then by default, the container returns a Collection of objects whose type is the local bean interface type.

      You can change this to the remote bean interface with annotations or deployment XML configuration. For more information, see "Implementing an EJB 2.1 EJB QL Select Method".

Custom TopLink Select Methods

Using EJB 2.1, you can create custom TopLink select methods.

Using EJB 2.1, you can take advantage of the TopLink query and expression framework to define advanced select methods that can use any of the TopLink query and expression framework features, including Call, DatabaseQuery, Expression, EJB QL, and native SQL. For more information, see "Using TopLink Workbench".

What is a Message-Driven Bean?

A message-driven bean (MDB) is an EJB 3.0 or EJB 2.1 EJB component that functions as an asynchronous message consumer. An MDB has no client-specific state but may contain message-handling state such as an open database connection or object references to another EJB. A client uses an MDB to send messages to the destination for which the bean is a message listener.

Using OC4J, you can use an MDB with a variety of message providers (see "What Message Providers Can I use with My MDB?"). You associate the MDB with an existing message provider and the container handles much of the setup required, as follows:

The purpose of an MDB is to exist within a pool and to receive and process incoming messages from a message provider. The container invokes a bean from the queue to handle each incoming message from the queue. No object invokes an MDB directly: all invocation for an MDB comes from the container. After the container invokes the MDB, it can invoke other EJBs or Java objects to continue the request.

A MDB is similar to a stateless session bean because it does not save conversational state and is used for handling multiple incoming requests. Instead of handling direct requests from a client, MDBs handle requests placed on a queue. Figure 1-3 demonstrates this by showing how clients place requests on a queue. The container takes the requests off of the queue and gives the request to an MDB in its pool.

Figure 1-3 Message Driven Beans

Message Driven Bean Flow of Control
Description of "Figure 1-3 Message Driven Beans"

This section describes:

For more information, see:

What is the Message-Driven Bean Lifecycle?

The lifecycle for EJB 3.0 (see Table 1-17) and EBJ 2.1 (see Table 1-18) message-driven beans are identical. The difference is in how you register lifecycle callback methods.

Table 1-17 lists the optional EJB 3.0 message-driven bean lifecycle callback methods you can define using annotations. For EJB 3.0 message-driven beans, you do not need to implement these methods.

Table 1-17 Lifecycle Methods for an EJB 3.0 Message-Driven Bean

Annotation Description

@PostConstruct

This optional method is invoked for a message-driven bean before the first business method invocation on the bean. This is at a point after which any dependency injection has been performed by the container.

@PreDestroy

This optional method is invoked for a message-driven bean when the instance is in the process of being removed by the container. The instance typically releases any resources that it has been holding.


Table 1-18 lists the EJB 2.1 lifecycle methods, as specified in the javax.ejb.MessageDrivenBean interface, that a message-driven bean must implement. For EJB 2.1 message-driven beans, you must at the least provide an empty implementation for all callback methods.

Table 1-18 Lifecycle Methods for an EJB 2.1 Message-Driven Bean

EJB Method Description

ejbCreate

The container invokes this method right before it creates the bean. A message-driven bean must do nothing in this method.

ejbRemove

A container invokes this method before it ends the life of a MDB. Use this method to perform any required clean-up—for example, closing external resources such as file handles.


For more information, see:

What is Message Driven Context?

OC4J maintains a javax.ejb.MessageDrivenContext for each message-driven bean instance and makes this message-driven context available to the beans. The bean may use the methods in the message-driven context to make callback requests to the container.

In addition, you can use the methods inherited from EJBContext (see "What is EJB Context?").

For more information, see:

Which Type of EJB Should You Use?

This section describes:

Which Type of Session Bean Should You Use?

Stateless session beans are useful mainly in middle-tier application servers that provide a pool of beans to process frequent and brief requests.

When do you use Bean-Managed versus Container-Managed Persistence?

In practical terms, Table 1-19 provides a definition for both BMP and CMP, and a summary of the programmatic and declarative differences between them.

Table 1-19 Comparison of Bean-Managed and Container-Managed Persistence

Management Issues Bean-Managed Persistence Container-Managed Persistence

Persistence management

You are required to implement the persistence management within the ejbStore, ejbLoad, ejbCreate, and ejbRemove EntityBean methods. These methods must contain logic for saving and restoring the persistent data.

For example, the ejbStore method must have logic in it to store the entity bean's data to the appropriate database. If it does not, the data can be lost.

The management of the persistent data is done for you. That is, the container invokes a persistence manager on behalf of your bean.

You use ejbStore and ejbLoad for preparing the data before the commit or for manipulating the data after it is refreshed from the database. The container always invokes the ejbStore method right before the commit. In addition, it always invokes the ejbLoad method right after reinstating CMP data from the database.

Finder methods allowed

The findByPrimaryKey method and other finder methods are allowed.

The findByPrimaryKey method and other finder methods clause are allowed.

Defining CMP fields

N/A

Required within the EJB deployment descriptor. The primary key must also be declared as a CMP field.

Mapping CMP fields to resource destination

N/A

Required. Dependent on persistence manager.

Definition of persistence manager

N/A

Required within the Oracle-specific deployment descriptor. By default,OC4J uses the TopLink persistence manager.


With CMP, you can build components to the EJB 2.0 specification that can save the state of your EJB to any J2EE supporting application server and database without having to create your own low-level JDBC-based persistence system.

With BMP, you can tailor the persistence layer of your application at the expense of additional coding and support effort.

For more information, see:

What is the Difference Between Session and Entity Beans?

The major differences between session and entity beans are that entity beans involve a framework for persistent data management, a persistent identity, and complex business logic. Table 1-20 illustrates the different interfaces for session and entity beans. Notice that the difference between the two types of EJBs exists within the bean class and the primary key. All of the persistent data management is done within the bean class methods.

Table 1-20 Session and Entity Bean Differences

J2EE Subject Entity Bean Session Bean

Local interface

Extends javax.ejb.EJBLocalObject

Extends javax.ejb.EJBLocalObject

Remote interface

Extends javax.ejb.EJBObject

Extends javax.ejb.EJBObject

Local Home interface

Extends javax.ejb.EJBLocalHome

Extends javax.ejb.EJBLocalHome

Remote Home interface

Extends javax.ejb.EJBHome

Extends javax.ejb.EJBHome

Bean class

Extends javax.ejb.EntityBean

Extends javax.ejb.SessionBean

Primary key

Used to identify and retrieve specific bean instances

Not used for session beans. Stateful session beans do have an identity, but it is not externalized.