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
 

2 Understanding EJB Application Development

This chapter describes:

How Should You Develop EJB Applications?

This section describes:

Understanding the EJB Application Directory Structure

Although you can develop your application in any manner, we encourage you to use consistent naming to locate your application easily. One method would be to implement your enterprise Java application under a single parent directory structure, separating each module of the application into its own subdirectory.

Notice in Figure 2-1 that the EJB and Web modules exist under the hello application parent directory and are developed separately in their own directory.

Figure 2-1 Hello Directory Structure

Directory structure
Description of "Figure 2-1 Hello Directory Structure"


Note:

For EJB modules, the top of the module (ejb_module) represents the start of a search path for classes. As a result, classes belonging to packages are expected to be located in a nested directory structure beneath this point. For example, a reference to a package class myapp.Hello.class is expected to be located in ...hello/ejb_module/myapp/Hello.class.

Using EJB Development Tools

This section describes developing EJB applications:

Using JDeveloper

Oracle JDeveloper greatly simplifies J2EE application development by providing extensive automation, a built-in OC4J for rapid deployment and testing, and many other productivity enhancements. For example:

For more information on JDeveloper, see http://www.oracle.com/technology/products/jdev/index.html.

Using Eclipse

Oracle is developing extensible frameworks and exemplary tools on the Eclipse platform for the definition and editing of Object-Relational (O/R) mappings for EJB 3.0 Entities. EJB 3.0 O/R mapping support will focus on minimizing the complexity of mapping by providing creation and automated initial mapping wizards, and programming assistance such as dynamic problem identification

For more information on EJB 3.0 support in Eclipse, see http://www.eclipse.org/dali/.

Using TopLink Workbench

You can use the TopLink Workbench to create and configure:

  • EJB 3.0 toplink-ejb-jar.xml and ejb3-toplink-sessions.xml files

  • EJB 2.1 toplink-ejb-jar.xml file

  • ejb-jar.xml file

For more information, see:

What OC4J Services Can You Use with an EJB?

Table 2-1 lists some of the important services that OC4J provides and shows the EJB types you can use them with.

Footnote 1 EJB 2.1 only.

Footnote 2 EJB 2.1 only.

For more information on OC4J services, see the appropriate OC4J guide as shown in Table 2-2:

Table 2-2 Location of Information for J2EE Subjects

J2EE Subject The Subject is Documented in this OC4J Documentation Book

JNDI

Oracle Containers for J2EE Services Guide


Data Source

Oracle Containers for J2EE Services Guide


RMI and RMI/IIOP

Oracle Containers for J2EE Services Guide


Transactions (JTA)

Oracle Containers for J2EE Services Guide

Security

Oracle Containers for J2EE Security Guide


CSiV2

Oracle Containers for J2EE Services Guide


JMS

Oracle Containers for J2EE Services Guide


Clustering

Oracle Containers for J2EE Services Guide


Timers

Oracle Containers for J2EE Services Guide


J2CA

Oracle Containers for J2EE Services Guide


Java Object Cache

Oracle Containers for J2EE Services Guide


Web Services

Oracle Application Server Web Services Developer's Guide

HTTPS

Oracle Containers for J2EE Services Guide


Optimization

Oracle Application Server Performance Guide


Default Persistence

Oracle TopLink Developer's Guide



How do You Package and Deploy an EJB Application?

This section describes the following:

General Packaging and Deployment Procedure

In general, to package and deploy an EJB application:

  1. Create the Deployment Descriptor

    After implementing and compiling your classes, you must create the standard J2EE EJB deployment descriptor for all beans in the module. The XML deployment descriptor (defined in the ejb-jar.xml file) describes the EJB module of the application. It describes the types of beans, their names, and attributes. The structure for this file is defined by the XML schema document (XSD) at http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd.

    Any EJB container services that you want to configure are designated in the deployment descriptor. For information, see "What OC4J Services Can You Use with an EJB?".

    You can also configure OC4J-specific options in the orion-ejb-jar.xml file (or using Application Server Control after deployment). For more information, see:

    After creation, place the deployment descriptors for the EJB application in the META-INF directory that is located in the same directory as the EJB classes (see Figure 2-1).

    The following example shows the sections that are necessary for the Hello example, which implements both a remote and a local interface.

    Example 2-1 shows the deployment descriptor for a version of the Hello example that uses a stateless session bean. This example defines both the local and remote interfaces. You do not have to define both interface types; you may define only one of them.

    Example 2-1 ejb-jar.xml Deployment Descriptor for Hello Bean Application

    <?xml version="1.0" encoding="UTF-8" ?>
    <ejb-jar 
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                            http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"
        version="2.1">
       <enterprise-beans>
          <session>
             <description>no description</description>
             <display-name>HelloBean</display-name>
             <ejb-name>HelloBean</ejb-name>
             <home>hello.HelloHome</home>
             <remote>hello.Hello</remote>
             <local-home>hello.HelloLocalHome</local-home>
             <local>hello.HelloLocal</local>
             <ejb-class>hello.HelloBean</ejb-class>
             <session-type>Stateless</session-type>
             <transaction-type>Container</transaction-type>
          </session>
       </enterprise-beans>
    
       <assembly-descriptor>
          <container-transaction>
             <method>
                <ejb-name>HelloBean</ejb-name>
                <method-name>*</method-name>
             </method>
             <trans-attribute>Supports</trans-attribute>
          </container-transaction>
          <security-role>
             <role-name>users</role-name>
          </security-role>
       </assembly-descriptor>
    </ejb-jar>
    
    
  2. Archive the EJB Application

    After you have finalized your implementation and created the deployment descriptors, archive your EJB application into a JAR file. The JAR file should include all EJB application files and the deployment descriptor.


    Note:

    If you have included a Web application as part of this enterprise Java application, follow the instructions for building the Web application in the Oracle Containers for J2EE Developer's Guide.

    For example, to archive your compiled EJB class files and XML files for the Hello example into a JAR file, perform the following in the .../hello/ejb_module directory:

    % jar cvf helloworld-ejb.jar .
    
    

    This archives all files contained within the ejb_module subdirectory within the JAR file.

  3. Prepare the EJB Application for Assembly

    To prepare the application for deployment, you do the following:

    1. Modify the application.xml file with the modules of the enterprise Java application.

      The application.xml file acts as the manifest file for the application and contains a list of the modules that are included within your enterprise application. You use each <module> element defined in the application.xml file to designate what comprises your enterprise application as Table 2-3 shows.

      Table 2-3 Module Elements in the application.xml File

      Element Contents

      <ejb>

      EJB JAR filename

      <web>

      Web WAR filename in the <web-uri> sub-element, and its context in the <context> sub-element

      <java>

      Client JAR filename, if any


      As Figure 2-1 shows, the application.xml file is located under a META-INF directory under the parent directory for the application. The JAR, WAR, and client JAR files should be contained within this directory. Because of this proximity, the application.xml file refers to the JAR and WAR files only by name and relative path—not by full directory path. If these files were located in subdirectories under the parent directory, then these subdirectories must be specified in addition to the filename.

      Example 2-2 modifies the <ejb>, <web>, and <java> module elements within application.xml for the Hello EJB application that also contains a Java client that interacts with the EJB.

      Example 2-2 application.xml Deployment Descriptor for Hello Bean

      <?xml version="1.0"?>
      <!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN" "http://java.sun.com/j2ee/dtds/application_1_2.dtd">
      <application>
        <display-name>helloworld j2ee application</display-name>
        <description>
           A sample J2EE application that uses a Helloworld Session Bean
           on the server and calls from java/servlet/JSP clients.
        </description>
        <module>
          <ejb>helloworld-ejb.jar</ejb>
        </module>
        <module>
          <web>
            <web-uri>helloworld-web.war</web-uri>
            <context-root>/helloworld</context-root>
          </web>
        </module>
        <module>
          <java>helloworld-client.jar</java>
        </module>
      </application>
      
      
    2. Archive all elements of the application into an EAR file.

      Create the EAR file that contains the JAR, WAR, and XML files for the application. Note that the application.xml file serves as the EAR manifest file.

      To create the helloworld.ear file, execute the following in the hello directory contained in Figure 2-1:

      % jar cvf helloworld.ear . 
      
      

      This step archives the application.xml, the helloworld-ejb.jar, the helloworld-web.war, and the helloworld-client.jar files into the helloworld.ear file.

Understanding EJB Deployment Descriptor Files

This section describes the various EJB deployment descriptor files that you use in EJB applications deployed to OC4J.

Table 2-4 lists the various EJB deployment descriptor files that you use in EJB applications deployed to OC4J. For each deployment descriptor file, it indicates the EJB types the deployment descriptor applies to and whether or not the deployment descriptor is optional, required, or not applicable to the EJB specification you are using.

Table 2-4 OC4J EJB Deployment Descriptor Files

Deployment Descriptor File Session Bean Entity Entity Bean Message- Driven Bean EJB 3.0 EJB 2.1

What is the ejb-jar.xml File?


Supported
Supported
Supported
Supported

Optional

Required

What is the orion-ejb-jar.xml File?


Not Supported
Supported
Supported
Supported

Optional

Optional

What is the toplink-ejb-jar.xml File?


Not Supported
Supported
Supported
Not Supported

Optional

Required

What is the ejb3-toplink-sessions.xml File?


Not Supported
Supported
Not Supported
Not Supported

Optional

Not Applicable

What is the persistence.xml File?


Not Supported
Supported
Not Supported
Not Supported

Optional

Not Applicable

What is the orm.xml File?


Not Supported
Supported
Not Supported
Not Supported

Optional

Not Applicable


Understanding Packaging

The J2EE architecture provides a variety of ways to package (or assemble) your application and its various J2EE components.

For more information, see "Packaging an EJB Application".

Understanding Deployment

After you package your J2EE application, to execute the application and make it available to end users, you deploy it to OC4J.

This section describes:

For more information, see "Deploying an EJB Application to OC4J ".

How Do Specify Vendor-Specific Configuration in an EJB 3.0 Application?

When you deploy an EJB 3.0 application, you must specify any vendor-specific configuration in one of the following ways:

  • Package an orion-ejb-jar.xml with the desired vendor-specific configuration and deploy.

  • After deployment, use the Application Server Control deployment profile to make the vendor-specific configuration.

For example, you can use annotations to define security roles but defining role-to-group mappings requires vendor-specific configuration. In this case, you can either define the role-to-group mappings in an orion-ejb-jar.xml file and package that in your application or, you can deploy your application without an orion-ejb-jar.xml and use Application Server Control to make this vendor-specific configuration after deployment.

How Does OC4J Determine What Type of Persistence to Use?

OC4J supports the following persistence APIs:

  • TopLink EJB 3.0 entity manager

  • TopLink EJB 2.1 persistence manager

  • Orion EJB 2.0 persistence manager (deprecated)

OC4J infers what type of persistence to use based on the type of object-relational mappings you define and the presence or absence of certain deployment XML files.

EJB 3.0 Applications

OC4J uses the TopLink entity manager if you deploy EJB 3.0 entities in an ejb.jar without an ejb-jar.xml file or if OC4J detects one or more EJB 3.0 annotations.

For more information, see:

EJB 2.x Applications

For EJB 2.1 or EJB 2.0 applications, OC4J uses the following algorithm to choose a persistence manager:

if (there is a <persistence-manager> specified)
{
    if (name == "orion")
    {
        use orion cmp
    }
    else
    {
        use TopLink cmp // default
    }
}
else
{
    if (there is a toplink-ejb-jar.xml)
    {
        use TopLink cmp
    }
    else if (there are orion cmp mappings)
    {
        use orion cmp
    }
    else
    {
        use TopLink cmp
    }
}

Table 2-5 summarizes this algorithm by developer action. For example, if you deploy a CMP application without a toplink-ejb-jar.xml file, OC4J uses the TopLink persistence manager and creates default TopLink object-relational mappings.

Table 2-5 OC4J EJB 2.x Persistence Manager Selection

Developer Action toplink-ejb-jar.xml orion-ejb-jar.xml Persistence Manager Mapping Type
  1. Deploy.

Absent

Optional; if present, contains no mappings and no <persistence-manager> element.

Toplink

Default TopLink mappings

  1. Deploy.

Present

Optional; if present, contains no mappings and no <persistence-manager> element.

Toplink

TopLink mappings as specified in toplink-ejb-jar.xml (default persistence manager properties)

  1. Edit the orion-ejb-jar.xml file to set <persistence-manager> element name attribute to toplinkFoot 1 .

  2. Edit additional persistence-manager subentriesFootref 1.

  3. Deploy.

Present

Optional; if present, contains no mappings

Toplink

TopLink mappings as specified in toplink-ejb-jar.xml (custom persistence manager properties)

  1. Deploy.

Absent

Present and contains Orion mappings; <persistence-manager> element is optional.

Orion

Orion mappings as specified in orion-ejb-jar.xml

  1. Edit the orion-ejb-jar.xml file to set <persistence-manager> element name attribute to orionFootref 1.

  2. Deploy.

Absent

Optional; if present, contains no mappings

Orion

Default Orion mappings


Footnote 1 See "Persistence Manager Section (persistence-manager)".

For more information, see:

In What Order does OC4J Deploy EJB Modules?

OC4J deploys EJB modules in the order in which they appear in the application.xml deployment descriptor. In general, loading order is component-specific and based on natural ordering for each component type.

For example, consider the application.xml file shown in Example 2-3.

Example 2-3 application.xml

<application>
  <display-name>master-application</display-name>
  <module>
    <ejb>ejb1.jar</ejb>
  </module>
  <module>
    <ejb>ejb2.jar</ejb>
  </module>
  <module>
    <java>appclient.jar</java>
  </module>
  <module>
    <web>
        <web-uri>clientweb.war</web-uri>
        <context-root>webapp</context-root>
    </web>
  </module>
  <module>
    <ejb>ejb3.jar</ejb>
  </module>

Based on this application.xml file, OC4J will load components in the following order:

  1. ejb1

  2. ejb2

  3. ejb3

  4. clientweb.war

  5. appclient.jar

What is the ejb-jar.xml File?

The ejb-jar.xml file is an EJB deployment descriptor file, and, when used, it describes the following:

  • mandatory structural information about all included enterprise beans

  • a descriptor for container managed relationships, if any

  • an optional name of an ejb-client-jar file for the ejb-jar

  • an optional application-assembly descriptor

When it is required, the ejb-jar.xml file describes EJB information applicable to any J2EE application server. This information may be augmented by application server-specific EJB deployment descriptor files (see "What is the orion-ejb-jar.xml File?" and "What is the toplink-ejb-jar.xml File?").

For more information, see "Configuring the ejb-jar.xml File".

EJB 3.0

If you are using EJB 3.0, this deployment descriptor file is optional: you can use annotations instead. In this release, OC4J supports the use of both EJB 3.0 annotations and ejb-jar.xml for all options except object-relational entity mapping configuration (see "Implementing an EJB 3.0 Entity"): all object-relational entity mapping configuration must done using annotations only. Configuration in the ejb-jar.xml file overrides annotations.

EJB 2.1

If you are using EJB 2.1, this deployment descriptor file is required.

XML Reference

The XML reference for this deployment descriptor file depends on the EJB version you are using.

For EJB 3.0, this deployment descriptor file conforms to the XML schema document located at http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd.

For EJB 2.1, this deployment descriptor file conforms to the XML schema document located at http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd.


Note:

In this release (10.1.3.0.0), OC4J support for EJB 3.0 features is based on a pre-release version of EJB 3.0. Consequently, OC4J support for some EJB 3.0 features may differ from what is specified in the ejb-jar_3_0.xsd (for example, interceptors and lifecycle listeners). For a list of options that OC4J does not support, see the Oracle Application Server Release Notes.

You may need to make code changes to your EJB 3.0 OC4J application after the EJB 3.0 specification is finalized and OC4J is updated to full EJB 3.0 compliance.


What is the orion-ejb-jar.xml File?

The orion-ejb-jar.xml file is an EJB deployment descriptor file that contains all OC4J-proprietary options. This file extends the configuration that you specify in the ejb-jar.xml file (see "What is the ejb-jar.xml File?").

For more information, see "Configuring the orion-ejb-jar.xml File".

EJB 3.0

If you are using EJB 3.0, this file is mandatory for all OC4J-proprietary options because there are no OC4J-proprietary annotations. Alternatively, you could deploy without an orion-ejb-jar.xml file and configure OC4J-proprietary options with Application Server Control (see "How Do Specify Vendor-Specific Configuration in an EJB 3.0 Application?").

EJB 2.1

If you are using EJB 2.1, this file is mandatory for all OC4J-proprietary options.

XML Reference

This deployment descriptor file conforms to the XML schema document at http://www.oracle.com/technology/oracleas/schema/orion-ejb-jar-10_0.xsd.

What is the toplink-ejb-jar.xml File?

The toplink-ejb-jar.xml file (also known as the TopLink project.xml file) is a TopLink persistence configuration descriptor file, and, when used, it describes TopLink project-level options (see "" in the Oracle TopLink Developer's Guide) such as TopLink descriptors and mappings.

For more information, see "Configuring the toplink-ejb-jar.xml File".

EJB 3.0

If you are using EJB 3.0, this file is only used to customize TopLink persistence manager configuration (see "Customizing the TopLink Entity Manager"). If you use this file to customize the TopLink persistence manager, you must also use an ejb3-toplink-sessions.xml file (see "What is the ejb3-toplink-sessions.xml File?").

EJB 2.1

If you are using EJB 2.1, this file is optional. If you omit this file from your application, you can configure OC4J to automatically construct it for your (see "Configuring Default Mappings"). Alternatively, you can use this file to configure TopLink persistence options yourself (see "Customizing the TopLink Persistence Manager").

XML Reference

The toplink-ejb-jar.xml file conforms to the XML schema documents located at <OC4J_HOME>\toplink\config\xsds. Oracle does not recommend manual configuration of this file. To create and configure this file, use the TopLink Workbench (see "Understanding the TopLink Workbench" in the Oracle TopLink Developer's Guide).

What is the ejb3-toplink-sessions.xml File?

The ejb3-toplink-sessions.xml file is a TopLink persistence configuration descriptor file, and, when used, it describes TopLink session-level options (see "Configuring Server Sessions" in the Oracle TopLink Developer's Guide) such as data sources, login information, caching options, and logging. It is equivalent to the sessions.xml file that TopLink users are familiar with.

This file provides a reference to the primary project (see "What is the toplink-ejb-jar.xml File?"), if used.

For more information, see "Configuring the ejb3-toplink-sessions.xml File".

EJB 3.0

If you are using EJB 3.0, this file is only used to customize TopLink persistence manager configuration (see "Customizing the TopLink Entity Manager"). If you use this file to customize the TopLink persistence manager, you may also use a toplink-ejb-jar.xml file (see "What is the toplink-ejb-jar.xml File?").

EJB 2.1

If you are using EJB 2.1, this file is not used.

XML Reference

The ejb3-toplink-sessions.xml file conforms to the XML schema documents located at <OC4J_HOME>\toplink\config\xsds. Oracle does not recommend manual configuration of this file. To create and configure this file, use the TopLink Workbench (see "Understanding the TopLink Workbench" in the Oracle TopLink Developer's Guide).

What is the persistence.xml File?

The persistence.xml file is a persistence descriptor file that you use to define one or more persistence units in an EJB 3.0 application that uses entities. A persistence unit defines an entity manager's configuration. You specify a persistence unit by name when you acquire an entity manager (see "Acquiring an EntityManager"). Alternatively, you can take advantage of the OC4J default persistence unit (see "Understanding the OC4J Default Persistence Unit").

A persistence unit is a logical grouping of:

  • Entity manager: including, entity manager provider, the entity managers obtained from it, and entity manager configuration.

  • Persistent managed classes: the classes you intend to manage using an entity manager, namely, entity classes, embeddable classes, and mapped superclasses (see "What Persistent Managed Classes Does this Persistence Unit Include?").

  • Mapping metadata: the information that describes how to map persistent managed classes to database tables. You can specify mapping metadata using annotations on persistent managed classes and orm.xml files (see "What is the orm.xml File?").

You can package a persistence.xml file in any of the following:

  • EJB-JAR file

  • WAR file

    • WEB-INF/classes directory

    • WEB-INF/lib (in this case, persistence.xml file must be in a JAR)

  • EAR

    • persistence.xml file in a JAR in root of EAR

    • persistence.xml file in a JAR in the EAR library directory

  • Application client JAR

The JAR file or directory whose META-INF directory contains the persistence.xml file is called the root of the persistence unit. An EJB 3.0 application that uses entities must define at least one persistence unit root.

The scope of a persistence unit is determined by where you define its persistence unit root:

  • EJB-JAR, WAR, or application client jar:

    • Scoped to that EJB-JAR, WAR, or application jar respectively

    • Visible to the components defined in that EJB-JAR, WAR, or application jar

    • Not visible as a persistence unit to other parts of the application

  • EAR:

    • Scoped to application as a whole

    • Generally visible to all components in the application

Each persistence unit must have a name. Only one persistence unit of a given name may exist in a given EJB-JAR, WAR, EAR, or application client JAR.


Note:

A persistence unit of the same name defined at the EJB-JAR, WAR, or application client JAR level overrides that defined at the EAR level. That is, the EAR-level persistence unit will not be visible to the components defined by that EJB-JAR, WAR, or application JAR file

For more information, see "Configuring the persistence.xml File".

Understanding the OC4J Default Persistence Unit

OC4J provides a default persistence unit capability that you can use to simplify deployment descriptor configuration and client code that accesses entity managers.

If you specify one and only one persistence unit in a persistence.xml file, then when you acquire an entity manager in that persistence unit's scope, you do not need to specify the persistence unit by name. In this case, OC4J will use the single persistence unit you specified.

If your application requires only one persistence unit and you deploy EJB 3.0 entities without a persistence.xml file, OC4J will create a default persistence unit and use it to satisfy your application code when it acquires an entity manager (see "Acquiring the OC4J Default Entity Manager in an EJB 3.0 Stateful Session Bean Client"). In this case, OC4J assumes that all EJB 3.0 entity classes belong to the default persistence unit. To disable this feature, set orion-ejb-jar.xml file attribute disable-default-persistent-unit to true.

If you set disable-default-persistent-unit to true, you can still use the OC4J default persistence unit if you specify an empty persistence unit (see "Configuring the persistence.xml File for the OC4J Default Persistence Unit") in a persistence.xml file, then when you acquire an entity manager in that persistence unit's scope, you do not need to specify a persistence unit name. In this case, OC4J will use its own default persistence unit and will assume that all EJB 3.0 entity classes in the persistence unit root belong to that persistence unit. You may specify one and only one such empty persistence unit in your application.

For more information, see:

EJB 3.0

If you are using EJB 3.0 entities, this file is mandatory (unless you are using the OC4J default persistence unit).

EJB 2.1

If you are using EJB 2.1, this file is not used.

XML Reference

For EJB 3.0, this deployment descriptor file conforms to the XML schema document defined in the EJB 3.0 specification at http://java.sun.com/products/ejb/docs.html.

What is the orm.xml File?

The orm.xml file is the XML deployment descriptor you use to specify object/relational mapping configuration. You can use an orm.xml file to as an alternative to annotations and to override annotations.

You can package an orm.xml file in any of the following:

  • META-INF directory of the persistence unit root (the JAR file or directory whose META-INF directory contains the persistence.xml file)

  • META-INF directory of any JAR file referenced by the persistence.xml file

  • persistence.xml file <persistence-unit> element <mapping-file> sub-element

You can specify more than one orm.xml file and these files may be present anywhere on the class path.

For more information, see:

EJB 3.0

If you are using EJB 3.0 entities, this file is optional.

EJB 2.1

If you are using EJB 2.1, this file is not used.

XML Reference

For EJB 3.0, this deployment descriptor file conforms to the XML schema document defined in the EJB 3.0 specification at http://java.sun.com/products/ejb/docs.html.

How Do You Use an EJB in Your Application?

In general, you use an EJB from a client (see "Understanding Client Access").

You can also use EJBs to implement fine-grained control over method invocation flow (see "Understanding EJB 3.0 Interceptors").

You can also use EJBs with Web services, either as a Web service client or as a Web service endpoint (see "Understanding EJBs and Web Services").

In a deployed EJB application, you can exploit the component nature of a J2EE application to monitor and control EJB performance and resource utilization (see "Understanding EJB Administration").

Understanding Client Access

In general, you use an EJB from a client (see "What Type of Client Do You Have?") to perform application tasks such as conducting a session, persistence, or message handling. For more information, see "Accessing an EJB from a Client".

Understanding EJB 3.0 Interceptors

An interceptor is a method that you associate with an EJB 3.0 session bean or message-driven bean message listener method. When a client invokes a session bean business method or message-driven bean message listener method, OC4J intercepts the client invocation and invokes your interceptor method before allowing the client invocation to proceed.

This section describes:

For more information, see:


Note:

In this release, OC4J interceptor support does not comply with the functionality specified in the EJB 3.0 public review draft. If you use interceptors, you may need to make code changes to your EJB 3.0 OC4J application after the EJB 3.0 specification is finalized and OC4J is updated to full EJB 3.0 compliance. For more information, see "Understanding EJB Support in OC4J".

Interceptor Restrictions

You can use interceptors with:

  • stateless session beans

  • stateful session beans

  • message driven beans

OC4J applies an interceptor to all business methods of a bean.

In this release, you must define an interceptor as a method of the bean class to which it applies. You may define only one interceptor method for each class.

An interceptor method may not be a business method.

An interceptor method has the following signature:

public Object <METHOD>(InvocationContext) throws Exception

Within an interceptor, you can use the InvocationContext to access client invocation metadata (see "Interceptors and Invocation Context").

An interceptor must observe the following transaction restrictions:

  • Interceptor method invocations occur within the same transaction and security context as the business method for which they are invoked.

  • Interceptor methods can mark their transaction for rollback by throwing a runtime exception or by calling setRollbackOnly using its EJBContext object as follows:

    InvocationContext.getEJBContext().setRollbackOnly();
    
    

    Interceptors may cause this rollback before or after they call InvocationContext.proceed().

    For more information, see "Using a Rollback Strategy".

  • When using container-managed transactions (see "Container-Managed Transaction (CMT)"), interceptors must not use any resource-manager specific transaction management methods that would interfere with the container's demarcation of transaction boundaries. For example, the interceptor must not use the following methods of the java.sql.Connection interface: commit, setAutoCommit, and rollback; or the following methods of the javax.jms.Session interface: commit and rollback. Interceptors must not attempt to obtain or use the javax.transaction.UserTransaction interface.

Interceptors and Invocation Context

Using the InvocationContext API, you can access (and modify) all the metadata relevant to the client invocation and implement fine grained control over method invocation flow by selectively choosing whether or not to allow the client invocation to proceed. Using EJB 3.0 interceptors, you can:

  • Modify parameters before they're passed to the bean

  • Modify the value returned from the bean

  • Catch and swallow method exceptions

  • Interrupt the call completely (for example, to implement your own security framework)

  • Provide method profiling

Understanding EJBs and Web Services

You can expose a stateless session bean as a Web service endpoint. Any EJB type can be the client of a Web service.

For more information, see "Using EJBs and Web Services".

Understanding EJB Administration

After you deploy your J2EE application, you can use J2EE administration features to monitor and optimize your application at runtime.

For more information, see:

Understanding EJB JNDI Services

The Java Naming and Directory Interface (JNDI) provides your J2EE application with a unified interface to multiple naming and directory services. You use JNDI to organize and locate components in a distributed J2EE environment.

You can define environment references for J2EE components and associated JNDI properties.

You can use JNDI to look up and retrieve these components using the:

For more information, see "Configuring JNDI Services".

Understanding EJB Data Source Services

A data source is a Java object that represents the physical enterprise information system to which OC4J persists entities. Your application uses a data source object to retrieve a connection to the enterprise information system the data source represents.

This section describes:

For more information, see:

What Types of Data Source does OC4J Support?

OC4J supports the following:

Table 2-6 lists the characteristics of these OC4J data sources.

Table 2-6 OC4J Data Source Type Characteristics

Characteristic Managed Native

Uses OC4J connection pool?

Yes

No

Connections can participate in global transactions?

Yes

No

Connections wrapped with an OC4J Connection proxy?

Yes

No


Managed Data Source

A managed data source (see Example 2-4) is an OC4J-provided implementation of the java.sql.DataSource interface that acts as a wrapper for a JDBC driver or data source. You can associate a managed data source with a separate connection pool. Multiple managed data sources may share the same connection pool.

Example 2-4 A Managed Data Source

<connection-pool name="ScottConnectionPool">
    <connection-factory
        factory-class="oracle.jdbc.pool.OracleDataSource"
        user="scott"
        password="tiger"
        url="jdbc:oracle:thin:@//localhost:1521/ORCL" >
    </connection-factory>
</connection-pool>
 
<managed-data-source
    name="OracleManagedDS"
    jndi-name="jdbc/OracleDS"
    connection-pool-name="ScottConnectionPool"
/>

For more information, see "Configuring a Data Source for an Oracle Database".

Native Data Source

A native data source (see Example 2-5) is a JDBC vendor-provided implementation of the java.sql.DataSource interface. You use the connection pool provided by the data source instance you choose. Each native data source must use its own connection pool.

Example 2-5 A Native Data Source

<native-data-source
    name="nativeDataSource"
    jndi-name="jdbc/nativeDS"
    description="Native DataSource"
    data-source-class="com.ddtek.jdbcx.sqlserver.SQLServerDataSource"
    user="frank"
    password="frankpw"
    url="jdbc:datadirect:sqlserver://server_name:1433;User=usr;Password=pwd">
</native-data-source>

For more information, see "Configuring a Data Source for a Third-Party Database".

How Do You Define a Connection URL in OC4J?

You specify a connection URL to tell OC4J where to find the underlying physical data source.

When you define a managed data source (see "Managed Data Source"), the connection URL is an attribute of the connection pool you associate with it (see Example 2-4).

When you define a native data source (see "Native Data Source"), the connection URL is an attribute of the native data source (see Example 2-5).

When specifying the connection URL to an Oracle database, you must use a service-based URL: that is, of the form host:port/SID (not host:port:SID), as Example 2-6 shows.

Example 2-6 OC4J Service-Based Connection URL

url="jdbc:oracle:thin:@//localhost:1521/ORCL"

When specifying the connection URL to a non-Oracle database, you use a URL appropriate for that system. Example 2-7 shows a typical connection URL for an SQLServer database.

Example 2-7 Non-Oracle Connection URL

url="jdbc:datadirect:sqlserver://server_name:1433;User=usr;Password=pwd">

What Transaction Types Do Data Sources Support?

Managed data sources support both local and global (two-phase commit) transactions. By default, they are configured to support global transactions. For more information, see "Configuring a Data Source for an Oracle Database").

Native data sources support only local transactions.

Where Do You Configure Data Source Information in OC4J?

In OC4J, you configure data source information in a data-sources.xml file.

You can include a data-sources.xml file in your EAR but OC4J does not support multiple data-sources.xml files.

For more information, see:

What is a Default Data Source?

To simplify application configuration, you can define default data sources.

How you define a default data source depends on the type of application you want to access the default data source from:

How Does OC4J Handle Multiple Data Sources?

OC4J does not support multiple data sources within different entities in orion-ejb-jar.xml.

If your application is composed of more than one EAR and each EAR contains a data-sources.xml, then, when you deploy your application, OC4J will use the last entity bean's data-source.xml for all entity beans.

To accommodate this scenario, specify the data source in orion-application.xml or specify a default data source.

For more information, see:

Understanding EJB Transaction Services

You can enable OC4J to manage transactions by using the Java Transaction API (JTA) supported by the Java Transaction Service (JTS). Using annotations or the deployment descriptor, you define the transactional properties of EJBs during design or deployment and then let OC4J take over the responsibility of transaction management.

Only flat transactions supported; nested transactions are not supported.

This section describes:

For more information, see:

Who Manages a Transaction?

A transaction can be managed by either the container (see "Container-Managed Transaction (CMT)") or the bean ("Bean-Managed Transaction (BMT)").

Container-managed transaction management is the default.

EJB 3.0 entities cannot be configured with a transaction management type. EJB 3.0 entities execute within the transactional context of the caller.

EJB 2.1 or EJB 1.1 entity beans must always use container-managed transaction demarcation. An EJB 2.1 or EJB 1.1 entity bean must not be designated with bean-managed transaction demarcation.

For all other EJB types, you can choose either container-managed or bean-managed transaction management.

Container-Managed Transaction (CMT)

When you use container-managed transactions, your EJB delegates to the container the responsibility to ensure that a transaction is started and committed when appropriate.

All session and message-driven beans and EJB 2.1 and EJB 1.1 entity beans can use CMT.

When developing an EJB that uses CMT, consider the following:

  • Do not use resource-manager specific transaction management methods such as java.sqlConnection methods commit, setAutoCommit, and rollback or javax.jms.Session methods commit or rollback.

  • Do not obtain or use the javax.transaction.UserTransaction interface.

  • A stateful session bean using CMT may implement the javax.ejb.SessionSynchronization interface.

  • An EJB that uses CMT may use javax.ejb.EJBContext methods setRollbackOnly and getRollbackOnly.

For an EJB that uses CMT, for each business method, you can also specify a transaction attribute that determines how the container manages transactions when a client invokes the method (see "How are Transactions Handled When a Client Invokes a Business Method?").

Bean-Managed Transaction (BMT)

When you use bean-managed transactions, the bean-provider is responsible for ensuring that a transaction is started and committed when appropriate.

Only session and message-driven beans can use BMT.

When developing an EJB that uses BMT, consider the following:

  • Use the javax.transaction.UserTransaction methods begin and commit to demarcate transactions.

  • A stateful session bean instance may, but is not required to, commit a started transaction before a business method returns.

    If a transaction has not been completed by the end of a business method, the container retains the association between the transaction and the instance across multiple client calls until the instance eventually completes the transaction.

  • A stateless session bean instance must commit a transaction before a business method or timeout callback method returns.

  • A message-driven bean instance must commit a transaction before a message listener method or timeout callback method returns.

  • After starting a transaction, do not use resource-manager specific transaction management methods such as java.sqlConnection methods commit, setAutoCommit, and rollback or javax.jms.Session methods commit or rollback.

  • A BMT bean must not use EJBContext methods getRollbackOnly and setRollbackOnly. It must use UserTransaction method getStatus and rollback instead.

How are Transactions Handled When a Client Invokes a Business Method?

For an EJB that uses CMT (see "Container-Managed Transaction (CMT)"), you can specify a transaction attribute for each of the following methods that determines how the container must manage transactions when a client invokes the method:

  • a method of a bean's business interface

  • a message listener method of a message-driven bean

  • a timeout callback method

  • a stateless session bean's Web service endpoint method

  • for EJB 2.1 and earlier, a method of a session or entity bean's home or component interface

OC4J starts a container-controlled transaction implicitly to satisfy the transaction attribute configuration when a bean method is invoked in the absence of a client-controlled transaction.

Table 2-7 shows what transaction (if any) an EJB method invocation uses depending on how its transaction attribute is configured and whether or not a client-controlled transaction exists at the time the method is invoked.

Table 2-7 EJB Transaction Support by Transaction Attribute

Transaction Attribute Client-Controlled Transaction Exists Client-Controlled Transaction Does Not Exist

NotSupported

Use no transaction

Use no transaction

Supports

Use client-controlled transaction

Use no transaction

RequiredFoot 1 

Use client-controlled transaction

Use container-controlled transaction

RequiresNew

Use client-controlled transaction

Use container-controlled transaction

Mandatory

Use client-controlled transaction

Exception raised

Never

Exception raised

Use no transaction


Footnote 1 Default.

Oracle recommends that you do not make modifications to entity beans under conditions identified as "Use no transaction". Oracle also recommends that you avoid using the Supports transaction attribute because it leads to a non-transactional state whenever the client does not explicitly provide a transaction.

How do I Participate in a Global or Two-Phase Commit Transaction?

If all resources enlisted in a transaction are XA-compliant then OC4J automatically coordinates a global or two-phase commit transaction.

In this release, transaction coordination functionality is now located in OC4J, replacing in-database coordination, which is now deprecated. Also, the middle-tier coordinator is now "heterogeneous", meaning that it supports all XA-compatible resources, not just those from Oracle.

The middle-tier coordinator provides the following features:

  • Supports any XA compliant resource

  • Supports interpositioning and transaction inflow

  • Last resource commit optimization

  • Recovery logging

For more information, see "Middle-Tier Two-Phase Commit (2PC) Coordinator" in the Oracle Containers for J2EE Services Guide.

Understanding EJB Security Services

You can configure your EJBs to use the J2EE security services that OC4J provides, including:

For more information, see:

Understanding Message Services

A message service provider is responsible for providing a destination to which clients can send messages and from which message-driven beans (see "What is a Message-Driven Bean?") can receive messages for processing.

Using EJB 3.0, message-driven beans can only use a JMS message service provider.

Using EJB 2.1, message-driven beans can use a JMS or non-JMS service provider.

In either case, you can configure a message service provider by specifying message service provider classes or by using a J2EE Connector Architecture (J2CA) adapter.

For more information, see:

What Message Providers Can I use with My MDB?

Using OC4J, you can use an MDB with the following types of message provider:

Oracle Application Server JMS (OracleAS JMS) Provider: File-Based

OracleAS JMS is a native Java JMS provider implementation that provides file-based persistence and is tightly integrated with OC4J. It is the default JMS provider included with OC4J. Figure 2-2 shows how a client sends an asynchronous request directly to the OracleAS JMS queue or topic that is located internally within OC4J. The MDB receives the message directly from OracleAS JMS.

Figure 2-2 Demonstration of an MDB Interacting with an OracleAS JMS Destination

Description of Figure 2-2 follows
Description of "Figure 2-2 Demonstration of an MDB Interacting with an OracleAS JMS Destination"

If you do not access OracleAS JMS using the Oracle JMS Connector (see "J2EE Connector Architecture (J2CA) Adapter Message Provider"), be aware of the following restrictions:

  • no support for two-phase commit (2PC)

For more information, see

Oracle JMS (OJMS) Provider: Advanced Queueing (AQ)-Based

Oracle JMS (OJMS) is the JMS interface to the Oracle Database Streams Advanced Queueing (AQ) feature. Oracle AQ is the Oracle database-integrated message queuing feature, built on the Oracle Streams information integration infrastructure that you install and configure within an Oracle database (see Figure 2-3).

Figure 2-3 Demonstration of an MDB Interacting with an OJMS Destination

Description of Figure 2-3 follows
Description of "Figure 2-3 Demonstration of an MDB Interacting with an OJMS Destination"

An MDB uses OJMS as follows:

  1. The MDB opens a JMS connection to the database using a data source with a username and password. The data source represents the Oracle JMS provider and uses a JDBC driver to facilitate the JMS connection.

  2. The MDB opens a JMS session over the JMS connection.

  3. Any message for the MDB is routed to the onMessage method of the MDB.

At any time, the client can send a message to the Oracle JMS topic or queue on which MDBs are listening. The Oracle JMS topic or queue is located in the database.

Before using Oracle JMS, you must create the appropriate queue or table in the database.


Note:

MDBs only work with certain versions of the Oracle database. See the certification matrix in the JMS chapter of the Oracle Containers for J2EE Services Guide for more information.

For more information, see:

J2EE Connector Architecture (J2CA) Adapter Message Provider

OC4J provides a JMS Connector: a generic Java Message Service (JMS) J2CA resource adapter that integrates OC4J with OracleAS JMS and OJMS message service providers, as well as non-Oracle JMS providers as Table 2-8 shows.

Table 2-8 Oracle JMS Connector Support for JMS Message Service Providers

JMS Provider Version

OracleAS JMS


all

OJMS

all

IBM WebSphere MQ-based JMS

Server Version 5.3 and 6.0

TIBCO Enterprise for JMS

3.1.0

SonicMQ

6.0


You can use other J2CA-compliant adapters with OC4J to integrate with other types of enterprise information systems (EIS).


Note:

Oracle recommends that newer JMS applications be deployed using the J2CA 1.5 Resource Adapter mandated by the J2EE 1.4 standard.

Using a J2CA adapter, you can access other JMS and non-JMS message service providers as Figure 2-4 shows. In this architecture, the client does not access a queue or topic directly. Instead, to send a message to an EIS by way of a J2CA adapter, you:

  1. Obtain a javax.resource.cci.ConnectionFactory.

    If the EIS is a JMS message service provider, there will likely be connection factory choices for queue or topic. For example, the Oracle JMS Connector offers a QueueConnectionFactory and a TopicConnectionFactory.

  2. Use the factory to obtain a javax.resource.cci.Connection.

  3. Use the connection to obtain a javax.resource.cci.Interaction.

  4. Configure the interaction and use Interaction method execute to send the message.

Figure 2-4 Demonstration of an MDB Interacting with a J2CA JMS Destination

Description of Figure 2-4 follows
Description of "Figure 2-4 Demonstration of an MDB Interacting with a J2CA JMS Destination"

From the perspective of OC4J, J2CA is only used as a means of accessing a message service provider for use with message-driven beans.

For more information, see:


Note:

For a complete code example of configuring a J2CA message service provider resource adapter and MDB application, see http://www.oracle.com/technology/tech/java/oc4j/1013/how_to/how-to-gjra-with-oracleasjms/doc/how-to-gjra-with-oracleasjms.html.

Understanding OC4J EJB Application Clustering Services

Oracle Application Server provides an extensive suite of high availability and failover options, including clustering: the distribution of application server and end-user application components across multiple hosts configured with the appropriate means of host-to-host communication.

OC4J application clustering is a state management service available to HTTP sessions and stateful session beans. In this context, a cluster is defined as two or more OC4J server nodes hosting the same set of applications. In this release, configuration has been simplified and made identical for both HTTP sessions and stateful session beans.


Note:

If you have a servlet (or other Web component) that invokes a stateful session bean, you must configure both HTTP session and stateful session bean clustering.

This section describes OC4J application clustering for stateful session beans, including:

For more information, see:

State Replication

When you configure a replication policy for a clustered OC4J EJB application, OC4J handles the replication of objects and values contained in stateful session bean instances. Only stateful session beans can be clustered. Because stateless session beans have no state to be replicated, they need not be clustered.

You must configure a replication policy to take advantage of failover (see "Failover"). If you only want to take advantage of load balancing, replication is not required (see "Load Balancing").

A replication policy determines the conditions (see "State Replication Trigger") under which bean state (see "State Replication Scope") is broadcast (see "State Replication Mode") to all other OC4J processes in the cluster.

Replication can have an impact on application server and network performance. The fewer times the state is sent out, the better your performance. However, there is a trade-off between performance and the confidence that the bean state is replicated to cover for all areas of the bean instance failing.

You can configure a replication policy globally for all applications deployed to an OC4J instance or at the application level. You can configure a replication policy for all Web and EJB components and you can configure a replication policy for EJB components only.

For more information on configuring a replication policy for a stateful session bean, see "Configuring EJB 3.0 and EJB 2.1 Stateful Session Bean Replication Policy".

State Replication Trigger

You can choose the condition that triggers replication as one of the following:

  • inherited — The stateful session bean uses the state replication trigger setting you configure at the application level. This is the default value.

  • on request end — The state of the stateful session bean is replicated to all hosts in the cluster (with the same multicast address, port) at the end of each EJB method call. If the node loses power, then the state has already been replicated. This method is less performant than the JVM termination replication mode, because the state is sent out more often. However, the guarantee for reliance is higher.

  • on shutdown — The state of the stateful session bean is replicated to only one other host in the cluster (with the same multicast address, port) when the JVM is terminating. This is the most performant option, because the state is replicated only once. However, it is not very reliable for the following reasons:

    • Your state is not replicated if the host is terminated unexpectedly.

    • The state of the bean exists only on a single host at any time; you carry a higher risk that the state does not replicate and is lost.

State Replication Scope

For stateful session beans, when replication is triggered, all the attributes of the stateful session bean are replicated (regardless of whether or not they have changed).

State Replication Mode

You can configure OC4J EJB application clustering in-memory replication by way of: multicast communication, peer-to-peer communication, or persistence of state data to a database. For more information on configuring replication type, see "Application Clustering in OC4J" in the Oracle Containers for J2EE Configuration and Administration Guide.

Load Balancing

Load balancing refers to how incoming client requests are distributed over all the OC4J instances in your cluster.

You can choose from among the following load balancing strategies:

Replication-Based Load Balancing

When you configure a replication policy for a clustered OC4J EJB application (see "State Replication"), OC4J can automatically select an OC4J instance at random from the pool of OC4J instances in the cluster when the first client request is serviced. You can configure how subsequent requests will be load balanced.

For more information, see "Configuring Replication-Based Load Balancing".

Static Retrieval Load Balancing

If you decide not to use EJB replication, but you want to load balance client requests across several statically specified OC4J processes, you can use static retrieval by providing the URLs for all of these processes in the JNDI URL property.

For more information, see "Configuring Static Retrieval Load Balancing".

DNS Load Balancing

If you decide not to use EJB replication, but you want to load balance client requests across several DNS-managed OC4J processes, you can use DNS retrieval by configuring your DNS server with a single hostname associated with the desired OC4J host IP addresses and specifying this hostname in the JNDI URL property.

For more information, see "Configuring DNS Load Balancing".

Failover

Failover requires that the state of the bean is replicated, so that when the original bean terminates unexpectedly, the request can be transparently forwarded to another OC4J process in the cluster.

For more information, see "State Replication".

Transactions

Transactions cannot failover. There is no reinstating an interrupted transaction in another bean. Instead, the transaction rolls back and must start over.

For more information, see "Understanding EJB Transaction Services".

Performance

The performance for clustering stateful session beans is dependent on the type of replication (see "State Replication") and load balancing (see "Load Balancing") options you choose.

You must choose the appropriate balance between replication frequency and robustness: the more frequently you replicate, the smaller the window of opportunity for losing state but the higher the load on the application server and network.

Understanding EJB Timer Services

You can set up a timer that invokes an EJB at a specified time, after a specified elapsed time, or at specified intervals. Timers are for use in modeling of application-level processes, not for real-time events.

Table 2-9 summarizes the timers you can use with enterprise JavaBeans.

Table 2-9 EJB Timers

Timer Stateful Session Bean Stateless Session Bean CMP Entity Bean BMP Entity Bean Message-Driven Bean

"Understanding J2EE Timer Services"







    EJB 3.0

Not Supported
Supported
Not Supported
Not Supported
Supported

    EJB 2.1

Not Supported
Supported
Supported
Supported
Supported

"Understanding OC4J Cron Timer Services"







    EJB 3.0

Not Supported
Supported
Not Supported
Not Supported
Supported

    EJB 2.1

Supported
Supported
Supported
Supported
Supported

For more information, see "Configuring Timer Services".

Understanding J2EE Timer Services

The EJB timer service is a container-managed service that provides methods to allow callbacks to be scheduled for time-based events. The container provides a reliable and transactional notification service for timed events. Timer notifications may be scheduled to occur at a specific time, after a specific elapsed duration, or at specific recurring intervals.The J2EE timer service is implemented by OC4J. An enterprise bean accesses this service by means of dependency injection, through the EJBContext interface, or through lookup in the JNDI namespace.

For more information, see:

Understanding OC4J Cron Timer Services

In the UNIX world, you can schedule a timer, known as a cron timer, to execute regularly at specified intervals. Oracle has extended OC4J to support cron timers with EJBs. You can use cron expressions for scheduling timer events with EJBs deployed to OC4J.

For more information, see "Configuring an EJB with an OC4J Cron Timer".