The sections that follow describe the EJB implementation process, and provide guidance for how to get an EJB up and running in WebLogic Server.
It is assumed that you understand WebLogic Server's value-added EJB features, have selected a design pattern for your application, and have made key design decisions.
For a review of WebLogic Server EJB features, see WebLogic Server Value-Added EJB Features.
For discussion of design options for EJBs, factors to consider during the design process, and recommended design patterns see Designing Enterprise JavaBeans.
This section is a brief overview of the EJB development process. It describes the key implementation tasks and associated results.
Figure 4-1 illustrates the process of developing an EJB. The steps in the process, and the results of each are described in Table 4-1. Subsequent sections detail each step in the process.
Figure 4-1 EJB Development Process Overview
Table 4-1 EJB Development Tasks and Results
Step | Description | Result |
---|---|---|
Create the directory structure for your source files, deployment descriptors, and files that are generated during the implementation process. |
A directory structure on your local drive. |
|
Create the classes that make up your bean. Insert appropriate tags in your source code to enable automatic generation of deployment descriptor elements later in the implementation process. |
|
|
Compile source code. |
|
|
Write or generate deployment descriptors that configure the runtime behavior and environment for the bean. |
|
|
You may need to edit deployment descriptors to ensure they correctly reflect all desired runtime behaviors for your bean. If your source was thoroughly annotated with markup that specifies the optional features the bean uses, and you used EJBGen to generate the deployment descriptors automatically, edits to your deployment descriptor should be minimal. |
|
|
Generate the container classes used to access the deployment unit, including classes for home and remote interfaces. |
Generated classes are added to archive or directory. |
|
Package compiled files, generated files, and deployment descriptors for deployment. If appropriate, you can leave your files unarchived in an exploded directory. |
Archive, either a JAR or an EAR |
|
Target the archive or application directory to desired Managed Server, or a WebLogic Server cluster, in accordance with selected staging mode. |
The deployment settings for the bean are written to |
Create a source directory where you will assemble the EJB.
Oracle recommends a split development directory structure, which segregates source and output files in parallel directory structures. For instructions on how to set up a split directory structure and package your EJB as an enterprise application archive (EAR), see "Overview of the Split Development Directory Environment" in Developing Applications for Oracle WebLogic Server.
If you prefer to package and deploy your EJB in a JAR file, create a directory for your class files, and within that directory, a subdirectory named META-INF
for deployment descriptor files.
The classes required depend on the type of EJB you are developing, as described in EJB Components..
Oracle offers productivity tools for developing class and interface files. The EJBGen command line utility automates the process of creating class and interface files, and also generates deployment descriptor files for the EJB. For more information and instructions for using these tools see EJBGen Reference.
The sections that follow provide tips and guidelines for using WebLogic Server-specific EJB features.
For each EJB type, WebLogic Server provides a generic class that contains Java callbacks, or listeners, that are required for most EJBs. The generic classes are in the weblogic.ejb
package:
GenericEnterpriseBean
GenericEntityBean
GenericMessageDrivenBean
GenericSessionBean
You can implement a generic bean template in a class of your own by importing the generic class into the class you are writing. This example imports the GenericSessionBean
class into HelloWorldEJB
:
import weblogic.ejb.GenericSessionBean; ... public class HelloWorldEJB extends GenericSessionBean {
The following sections provide guidelines for programming client access to an EJB.
Local clients obtain initial context using the getInitialContext
method, similar to the following excerpt.
Example 4-2 Local Client Performing a Lookup
... Context ctx = getInitialContexLt("t3://localhost:7001", "user1", "user1Password"); ... static Context getInitialContext(String url, String user, String password) { Properties h = new Properties(); "weblogic.jndi.WLInitialContextFactory"); h.put(Context.PROVIDER_URL, url); h.put(Context.SECURITY_PRINCIPAL, user); h.put(Context.SECURITY_CREDENTIALS, password); return new InitialContext(h); }
Remote clients obtain an InitialContext
from the WebLogic Server InitialContext
factory.
A client can look up the entity bean's home interface in one of two ways:
By following an EJB reference. This approach offers better performance than the alternative, looking up the home interface directly from the Java Naming and Directory Interface, and is a Oracle best practice. For instructions on using EJB references, see the following section, Using EJB Links.
Directly from the Java Naming and Directory Interface (JNDI). The container binds the entity bean's home interface in the global, server-side JNDI name space. For instructions see Programming JNDI for Oracle WebLogic Server.
Using EJB links is a Oracle best practice and WebLogic Server fully supports EJB links as defined in the EJB 2.1 Specification. You can link an EJB reference that is declared in one application component to an enterprise bean that is declared in the same Java EE application.
In the ejb-jar.xml
file, specify the link to the EJB using the ejb-link
element of the ejb-ref
element of the referencing application component. The value of ejb-link
must match that of the ejb-name
in both ejb-jar.xml
and weblogic-ejb-jar.xml
of the target EJB. The target EJB can be in any EJB JAR file in the same Java EE application as the referencing application component.
Because ejb-name
s are not required to be unique across EJB JAR files, you may need to provide the qualified path for the link. Use the following syntax to provide the path name for the EJBs within the same Java EE application.
<ejb-link>../products/product.jar#ProductEJB</ejb-link>
This reference provides the path name of the EJB JAR file that contains the referenced EJB with the appended ejb-name
of the target bean separated from the path by "#". The path name is relative to the referencing application component JAR file.
To enable an EJB to open an HttpURLConnection
to an external HTTP server using the java.net.URL
resource manager connection factory type, specify the URL, or specify an object bound in the JNDI tree that maps to a URL, using the resource-ref
element in ejb-jar.xml
and the res-ref-name
element in weblogic-ejb-jar.xml
.
To specify the URL to which an EJB sends requests:
In ejb-jar.xml
, specify the URL in the <jndi-name>
element of the resource-ref
element.
In weblogic-ejb-jar.xml
, specify the URL in the <jndi-name>
element of the resource-description
element:
<resource-description> <res-ref-name>url/MyURL</res-ref-name> <jndi-name>http://www.rediff.com/</jndi-name> </resource-description>
WebLogic Server creates a URL object with the jndi-name
provided and binds the object to the java:comp/env
.
To specify an object that is bound in JNDI and maps to a URL, instead of specifying a URL:
In ejb-jar.xml
, specify the name by which the URL is bound in JNDI in the <jndi-name>
element of the resource-ref
element.
In weblogic-ejb-jar.xml
, specify the name by which the URL is bound in JNDI in the <jndi-name>
element of the resource-description
element:
<resource-description> <res-ref-name>url/MyURL1</res-ref-name> <jndi-name>firstName</jndi-name> </resource-description>
where firstName
is the object bound to the JNDI tree that maps to the URL. This binding could be done in a startup class. When jndi-name
is not a valid URL, WebLogic Server treats it as an object that maps to a URL and is already bound in the JNDI tree, and binds a LinkRef
with that jndi-name
.
Regardless of how you specified an HTTP resource—by its URL or a JNDI name that maps to the URL—you can access it from EJB code in this way:
URL url = (URL) context.lookup("java:comp/env/url/MyURL"); connection = (HttpURLConnection)url.openConnection();
You can control the attributes of the network connection an EJB uses for communications by configuring a custom network channel and assigning it to the EJB. For information about WebLogic Server network channels and associated configuration instructions see "Configure Network Resources" in Configuring Server Environments for Oracle WebLogic Server. After you configure a custom channel, assign it to an EJB using the network-access-point
element in weblogic-ejb-jar.xml
.
Transaction design decisions are discussed in Transaction Design and Management Options. The following sections contain guidelines for programming transactions.
For information using transactions with entity beans, see Understanding ejbLoad() and ejbStore() Behavior.
Container-managed transactions are simpler to program than bean-managed transactions, because they leave the job of demarcation—starting and stopping the transaction—to the EJB container.
You configure the desired transaction behaviors in ejb-jar.xml
and weblogic-ejb-jar.xml
. For related information see Container-Managed Transactions Elements.
Key programming guidelines for container-managed transactions include:
Preserve transaction boundaries—Do not invoke methods that interfere with the transaction boundaries set by the container. Do not use:
The commit
, setAutoCommit
, and rollback
methods of java.sql.Connection
The getUserTransaction
method of javax.ejb.EJBContext
Any method of javax.transaction.UserTransaction
Roll back transactions explicitly—To cause the container to roll back a container-managed transaction explicitly, invoke the setRollbackOnly
method of the EJBContext
interface. (If the bean throws an application exception, typically an EJBException
, the rollback is automatic.)
Avoid serialization problems—Many data stores provide limited support for detecting serialization problems, even for a single user connection. In such cases, even with transaction-isolation in weblogic-ejb-jar.xml
set to TransactionSerializable
, exceptions or rollbacks in the EJB client might occur if contention occurs between clients for the same rows. To avoid such exceptions, you can:
Include code in your client application to catch SQL exceptions, and resolve them appropriately; for example, by restarting the transaction.
For Oracle databases, use the transaction isolation settings described in isolation-level.
In this release of WebLogic Server, you can specify that, if a business method that has started a transaction fails because of a transaction rollback that is not related to a system exception, the EJB container will start a new transaction and retry the failed method up to a specified number of times. If the method fails for the specified number of retry attempts, the EJB container throws an exception.
Note:
The EJB container does not retry any transactions that fail because of system exception-based errors.To configure automatic retry of container-managed transactions:
Make sure your bean is a container-managed session or entity bean.
You can configure automatic retry of container-managed transactions for container-managed session and entity beans only. You cannot configure automatic retry of container-managed transactions for message-driven beans because MDBs do not acknowledge receipt of a message they are processing when the transaction that brackets the receipt of the message is rolled back; messages are automatically retried until they are acknowledged. You also cannot configure automatic retry of container-managed transactions for timer beans because, when a timer bean's ejbTimeout method starts and is rolled back, the timeout is always retried.
Make sure the business methods for which you want to configure automatic retry of transactions are defined in the bean's remote or local interface or as home methods (local home business logic that is not specific to a particular bean instance) in the home interface; the methods must have one of the following container-managed transaction attributes:
RequiresNew
. If a method's transaction attribute (trans-attribute
element in ejb-jar.xml
) is RequiresNew
, a new transaction is always started prior to the invocation of the method and, if configured, automatic retry of transactions occurs if the transaction fails.
Required
. If a method's transaction attribute (trans-attribute
element in ejb-jar.xml
) is Required
, the method is retried with a new transaction only if the failed transaction was begun on behalf of the method.
For more information on:
Programming interfaces, see Create EJB Classes and Interfaces and Sun documentation.
The trans-attribute
element in ejb-jar.xml
, see trans-attribute
in Container-Managed Transactions Elements, and the Sun documentation.
Make sure the methods for which you want to enable automatic retry of transactions are safe to be re-invoked. A retry of a failed method must yield results that are identical to the results the previous attempt, had it been successful, would have yielded. In particular:
If invoking a method initiates a call chain, it must be safe to reinvoke the entire call chain when the method is retried.
All of the method's parameters must be safe for reuse; when a method is retried, it is retried with the same parameters that were used to invoke the failed attempt. In general, parameters that are primitives, immutable objects, or are references to read-only objects are safe for reuse. If a parameter is a reference to an object that is to be modified by the method, reinvoking the method must not negatively affect the result of the method call.
If the bean that contains the method that is being retried is a stateful session bean, the bean's conversational state must be safe to re-invoke. Since a stateful session bean's state is not transactional and is not restored during a transaction rollback, in order to use the automatic retry of transactions feature, you must first be sure the bean's state is still valid after a rollback.
Specify the methods for which you want the EJB container to automatically retry transactions and the number of retry attempts you want the EJB container to make in the retry-methods-on-rollback
element in weblogic-ejb-jar.xml
.
The retry-count
subelement to retry-methods-on-rollback can also be modified via the Administration Console.
This section contains programming considerations for bean-managed transactions. For a summary of the distinguishing features of bean-level transactions and a discussion of related design considerations, see Bean-Level Transaction Management.
Demarcate transaction boundaries—To define transaction boundaries in EJB or client code, you must obtain a UserTransaction
object and begin a transaction before you obtain a Java Transaction Service (JTS) or JDBC database connection. To obtain the UserTransaction
object, use this command:
ctx.lookup("javax.transaction.UserTransaction");
After obtaining the UserTransaction
object, specify transaction boundaries with tx.begin()
, tx.commit()
, tx.rollback()
.
If you start a transaction after obtaining a database connection, the connection has no relationship to the new transaction, and there are no semantics to "enlist" the connection in a subsequent transaction context. If a JTS connection is not associated with a transaction context, it operates similarly to a standard JDBC connection that has autocommit
equal to true
, and updates are automatically committed to the datastore.
Once you create a database connection within a transaction context, that connection is reserved until the transaction commits or rolls back. To optimize performance and throughput, ensure that transactions complete quickly, so that the database connection can be released and made available to other client requests.
Note:
You can associate only a single database connection with an active transaction context.Setting transaction isolation level—For bean-managed transactions, you define isolation level in the bean code. Allowable isolation levels are defined on the java.sql.Connection interface. F or information on isolation level behaviors, see isolation-level.
See Example 4-3 for a code sample.
Example 4-3 Setting Transaction Isolation Level in BMT
import javax.transaction.Transaction; import java.sql.Connection import weblogic.transaction.TxHelper: import weblogic.transaction.Transaction; import weblogic.transaction.TxConstants; User Transaction tx = (UserTransaction) ctx.lookup("javax.transaction.UserTransaction"); //Begin user transaction tx.begin(); //Set transaction isolation level to TransactionReadCommitted Transaction tx = TxHelper.getTransaction(); tx.setProperty (TxConstants.ISOLATION_LEVEL, new Integer (Connection.TransactionReadCommitted)); //perform transaction work tx.commit();
Avoid restricted methods—Do not invoke the getRollbackOnly
and setRollbackOnly
methods of the EJBContext
interface in bean-managed transactions. These methods should be used only in container-managed transactions. For bean-managed transactions, invoke the getStatus
and rollback methods of the UserTransaction
interface.
Use one connection per active transaction context—You can associate only a single database connection with an active transaction context.
This section describes two approaches for distributing a transaction across multiple beans, which may reside on multiple server instances.
The code fragment below is from a client application that obtains a UserTransaction
object and uses it to begin and commit a transaction. The client invokes two EJBs within the context of the transaction.
import javax.transaction.*; ... u = (UserTransaction) jndiContext.lookup("javax.transaction.UserTransaction"); u.begin(); account1.withdraw(100); account2.deposit(100); u.commit(); ...
The updates performed by the account1
and account2
beans occur within the context of a single UserTransaction
. The EJBs commit or roll back together, as a logical unit, whether the beans reside on the same server instance, different server instances, or a WebLogic Server cluster.
All EJBs called from a single transaction context must support the client transaction—each beans' trans-attribute
element in ejb-jar.xml
must be set to Required
, Supports
, or Mandatory
.
You can use a "wrapper" EJB that encapsulates a transaction. The client calls the wrapper EJB to perform an action such as a bank transfer, and the wrapper starts a new transaction and invokes one or more EJBs to do the work of the transaction.
The wrapper EJB can explicitly obtain a transaction context before invoking other EJBs, or WebLogic Server can automatically create a new transaction context, if the wrapper's trans-attribute
element in ejb-jar.xml
is set to Required
or RequiresNew
.
All EJBs invoked by the wrapper EJB must support the wrapper EJB's transaction context— their trans-attribute
elements must be set to Required
, Supports
, or Mandatory
.
WebLogic Server supports the EJB timer service defined in the EJB 2.1 Specification and EJB 3.0 Specification. The EJB timer service is an EJB-container provided service that allows you to create timers that schedule callbacks to occur when a timer object expires. Timer objects can be created for entity beans, message-driven beans, and stateless session beans. Timer objects expire at a specified time, after an elapsed period of time, or at specified intervals. For instance, you can use the timer service to send out notification when an EJB remains in a certain state for an elapsed period of time.
The WebLogic EJB timer service is intended to be used as a coarse-grained timer service. Rather than having a large number of timer objects performing the same task on a unique set of data, Oracle recommends using a small number of timers that perform bulk tasks on the data. For example, assume you have an EJB that represents an employee's expense report. Each expense report must be approved by a manager before it can be processed. You could use one EJB timer to periodically inspect all pending expense reports and send an email to the corresponding manager to remind them to either approve or reject the reports that are waiting for their approval.
You can configure two types of EJB timer services: clustered or local.
Clustered EJB timer services provide the following advantages:
Better visibility.
Timers are accessible from any node in a cluster. For example, the javax.ejb.TimerService.getTimers()
method returns a complete list of all stateless session or message-driven bean timers in a cluster that were created for the EJB. If you pass the primary key of the entity bean to the getTimers()
method, a list of timers for that entity bean are returned.
Automatic load balancing and failover.
Clustered EJB timer services take advantage of the load balancing and failover capabilities of the Job Scheduler.
For information about the configuring a clustered EJB timer service, see Configuring Clustered EJB Timers.
Local EJB timer services execute only on the server on which they are created and are visible only to the beans on that server. With a local EJB timer service, you do not have to configure a cluster, database, JDBC data source, or leasing service, as you do for clustered EJB timer services.
You cannot migrate a local EJB timer object from one server to another; timer objects can only be migrated as part of an entire server. If a server that contains EJB timers goes down for any reason, you must restart the server or migrate the entire server in order for the timers to execute.
This section summarizes the Java programming interfaces defined in the EJB 2.1 Specification that you can use to program timers. For detailed information on these interfaces, refer to the EJB 2.1 Specification. This section also provides details about the WebLogic Server-specific timer-related interfaces.
EJB 2.1 interfaces you can use to program timers are described in the following table.
Table 4-2 EJB 2.1 Timer-related Programming Interfaces
Programming Interface | Description |
---|---|
|
Implement for the enterprise bean class of a bean that will be registered with the timer service for timer callbacks. This interface has a single method, |
|
Access the timer service using the |
|
Create new EJB timers or access existing EJB timers for the EJB. |
|
Access information about a particular EJB timer. |
|
Define a serializable timer handle that can be persisted. Since timers are local objects, a |
For more information on EJB 2.1 timer-related programming interfaces, see the EJB 2.1 Specification.
WebLogic Server-specific interfaces you can use to program timers include:
weblogic.management.runtime.EJBTimerRuntimeMBean
—provides runtime information and administrative functionality for timers from a particular EJBHome
. The weblogic.management.runtime.EJBTimerRuntimeMBean
interface is shown in Example 4-4.
Example 4-4 weblogic.management.runtime.EJBTimerRuntimeMBean Interface
public interface weblogic.management.runtime.EJBTimerRuntimeMBean { public int getTimeoutCount(); // get the number of successful timeout notifications that have been made public int getActiveTimerCount(); // get the number of active timers for this EJBHome public int getCancelledTimerCount(); // get the number of timers that have been cancelled for this EJBHome public int getDisabledTimerCount(); // get the number of timers temporarily disabled for this EJBHome public void activateDisabledTimers(); // activate any temporarily disabled timers }
weblogic.ejb.WLTimerService
interface—extends the javax.ejb.TimerService
interface to allow users to specify WebLogic Server-specific configuration information for a timer. The weblogic.ejb.WLTimerService
interface is shown in Example 4-5; for information on the javax.ejb.TimerService
, see the EJB 2.1 Specification.
Note:
Theweblogic.ejb.WLTimerService
interface is not supported by the clustered EJB timer service, as described in Configuring Clustered EJB Timers.Example 4-5 weblogic.ejb.WLTimerService Interface
public interface WLTimerService extends TimerService { public Timer createTimer(Date initial, long duration, Serializable info, WLTimerInfo wlTimerInfo) throws IllegalArgumentException, IllegalStateException, EJBException; public Timer createTimer(Date expiration, Serializable info, WLTimerInfo wlTimerInfo) throws IllegalArgumentException, IllegalStateException, EJBException; public Timer createTimer(long initial, long duration, Serializable info WLTimerInfo wlTimerInfo) throws IllegalArgumentException, IllegalStateException, EJBException; public Timer createTimer(long duration, Serializable info, WLTimerInfo wlTimerInfo) throws IllegalArgumentException, IllegalStateException, EJBException; }
weblogic.ejb.WLTimerInfo
interface—used in the weblogic.ejb.WLTimerService
interface to pass WebLogic Server-specific configuration information for a timer. The weblogic.ejb.WLTimerInfo
method is shown in Example 4-6.
Note:
Theweblogic.ejb.WLTimerService
interface is not supported by the clustered EJB timer service, as described in Configuring Clustered EJB Timers.Example 4-6 weblogic.ejb.WLTimerInfo Interface
public final interface WLTimerInfo { public static int REMOVE_TIMER_ACTION = 1; public static int DISABLE_TIMER_ACTION = 2; public static int SKIP_TIMEOUT_ACTION = 3; /** * Sets the maximum number of retry attempts that will be * performed for this timer. If all retry attempts * are unsuccesful, the timeout failure action will * be executed. */ public void setMaxRetryAttempts(int retries); public int getMaxRetryAttempts(); /** * Sets the number of milliseconds that should elapse * before any retry attempts are made. */ public void setRetryDelay(long millis); public long getRetryDelay(); /** * Sets the maximum number of timeouts that can occur * for this timer. After the specified number of * timeouts have occurred successfully, the timer * will be removed. */ public void setMaxTimeouts(int max); public int getMaxTimeouts(); /** * Sets the action the container will take when ejbTimeout * and all retry attempts fail. The REMOVE_TIMER_ACTION, * DISABLE_TIMER_ACTION, and SKIP_TIMEOUT_ACTION fields * of this interface define the possible values. */ public void setTimeoutFailureAction(int action); public int getTimeoutFailureAction(); }
weblogic.ejb.WLTimer
interface—extends the javax.ejb.Timer
interface to provide additional information about the current state of the timer. The weblogic.ejb.WLTimer
interface is shown in Example 4-7.
Note:
Theweblogic.ejb.WLTimerService
interface is not supported by the clustered EJB timer service, as described in Configuring Clustered EJB Timers.The following deployment descriptor elements pertain to timers.
Table 4-3 Timer Deployment Descriptors
Element | Description |
---|---|
|
EJB timer object. |
|
Whether the EJB timer service is clustered or non-clustered. For information about the clustered EJB timer service, see Configuring Clustered EJB Timers. |
|
Name of a persistent store on the server's file system where WebLogic Server stores timer objects. |
For more information on these elements, see weblogic-ejb-jar.xml Deployment Descriptor Reference.
Note:
To review the advantages of using clustered EJB timers, see Clustered Versus Local EJB Timer Services.To configure the clustering of EJB timers, perform the following steps:
Ensure that you have configured the following:
A clustered domain. For more information, see "Setting up WebLogic Clusters" in Using Clusters for Oracle WebLogic Server.
Features of the Job Scheduler, including:
HA database, such as Oracle, DB2, Informix, MySQL, Sybase, or MSSQL.
JDBC data source that is mapped to the HA database using the <data-source-for-job-scheduler>
element in the config.xml
file.
Leasing service. By default, database leasing will be used and the JDBC data source defined by the <data-source-for-job-scheduler>
element in the config.xml
file will be used.
For more information about configuring the Job Scheduler, see "The Timer and Work Manager API" in Timer and Work Manager API (CommonJ) Programmer's Guide for Oracle WebLogic Server.
To enable the clustered EJB timer service, set the timer-implementation
element in the weblogic-ejb-jar.xml
deployment descriptor to Clustered
:
<timer-implementation>Clustered</timer-implementation>
For more information, see timer-implementation.
Please note the following changes in the behavior of the clustered EJB timer service:
The weblogic.ejb.WLTimer*
interfaces are not supported with clustered EJB timer services.
When creating a new clustered EJB timer using the createTimer()
method, you may notice a delay in timeout execution during the initial setup of the timer.
The Job Scheduler provides an "at least once" execution guarantee. When a clustered EJB timer expires, the database is not updated until the timer listener callback method completes. If the server were to crash before the database is updated, the timer expiration would be executed twice.
Timer configuration options related to the actions to take in the event of failure are not valid for the clustered EJB timer service. These configuration options include: retry delay, maximum number of retry attempts, maximum number of timeouts, and timeout failure actions.
The Job Scheduler queries the database every 30 seconds to identify timers that are due to expire. Execution may be delayed for timers with an interval duration less than 30 seconds.
Only transactional timers will be retried in the event of failure.
Fixed rate scheduling of timer execution is not supported.
This release of WebLogic Server complies with the EJB 2.1 requirements related to declaring and accessing external Web Services. Web Service references, declared in an EJB's deployment descriptor, maps a logical name for a Web Service to an actual Web Service interface, which allows you to refer to the Web Service using a logical name. The bean code then performs a JNDI lookup using the Web Service reference name.
For more information, see Getting Started With JAX-WS Web Services for Oracle WebLogic Server.
For a list of tools that support the compilation process, see Table 4-1.
For information on the compilation process, see Developing Applications for Oracle WebLogic Server.
If you annotate your Bean class file with JDK 1.5 annotations, you can use EJBGen to generate the Remote and Home classes and the deployment descriptor files for an EJB application.
Oracle recommends that you use EJBGen to generate deployment descriptors. For more information, see Appendix E, "EJBGen Reference."
Elements in ejb-jar.xml,
weblogic-ejb-jar.xml
, and for container-managed persistence entity beans, weblogic-cmp-jar.xml
, control the run-time characteristics of your application.
If you need to modify a descriptor element, you can edit the descriptor file with any plain text editor. However, to avoid introducing errors, use a tool designed for XML editing. Descriptor elements that you can edit with the WebLogic Server Administration Console are listed in Table 4-1.
The following sections are a quick reference to WebLogic Server-specific deployment elements. Each section contains the elements related to a type of feature or behavior. The table in each section defines relevant elements in terms of the behavior it controls, the bean type it relates to (if bean type-specific), the parent element in weblogic-ejb-jar.xml
that contains the element, and the behavior you can expect if you do not explicitly specify the element in weblogic-ejb-jar.xml
.
For comprehensive documentation of the elements in each descriptor file, definitions, and sample usage, refer to:
Appendix B, "weblogic-ejb-jar.xml Deployment Descriptor Reference"
Appendix C, "weblogic-cmp-jar.xml Deployment Descriptor Reference"
Your Sun documentation for elements in ejb-jar.xml
.
Note:
In the sections that follow, click the element name in the "Element" column to view detailed documentation on the element.This table lists the elements in weblogic-ejb-jar.xml
related to security.
Table 4-4 Security Elements in weblogic-ejb-jar.xml
Element | Description | Default |
---|---|---|
Maps security roles in Required if ejb-jar.xml defines application roles. |
none |
|
Additional Java security permission that is granted to this EJB. |
none |
|
Security principal name to use as the run-as principal for a bean that has specified a |
none |
|
Security options for beans that use the RMI-IIOP protocol. |
none |
This table lists the elements in weblogic-ejb-jar.xml
that map the names of beans or resources used in source code to their JNDI names in the deployment environment.
Table 4-5 Resource Mapping Elements in weblogic-ejb-jar.xml
Element | Bean Type | Description | Default |
---|---|---|---|
All |
JNDI name of a resource or reference available in WebLogic Server. Note: Assigning a JNDI name to a bean is not recommended. Global JNDI names generate heavy multicast traffic during clustered server startup. See Using EJB Links for the better practice. |
none |
|
All |
JNDI name for a bean's local home. If a bean has both a remote and a local home, then it must have two JNDI names; one for each home. |
none |
|
MDB |
JNDI name of the JMS connection factory that the bean uses to create queues and topics. |
|
|
MDB |
JNDI name that associates a message-driven bean with a queue or topic in the JNDI tree. |
none |
|
MDB |
Initial context factory that the EJB container uses to create connection factories. |
|
|
MDB |
Client ID for the message-driven bean associated with a durable subscriber topic. |
Value of ejb-name |
|
MDB |
|
n/a |
|
MDB |
Specifies the URL provider to be used by the |
|
This table lists elements in weblogic-ejb-jar.xml
that specify how the state of a bean is persisted.
Table 4-6 Persistence Elements in weblogic-ejb-jar.xml
Element | Bean Type | Description | Default |
---|---|---|---|
Entity |
Specifies EJB persistence type. WebLogic Server RDBMS-based persistence uses the identifier, |
n/a |
|
Entity |
Defines path, relative to the top level of the EJB's JAR deployment file or deployment directory, of the file that stores data for this persistence type. WebLogic Server RDBMS-based persistence generally uses an XML file named |
n/a |
|
Entity |
Version of the persistence type specified by type-identifier. For WebLogic 2.0 CMP persistence, use the value For WebLogic 1.1 CMP persistence, use the value 1.1. |
n/a |
|
Entity |
If true, the EJB container attempts to delay writing updates to a bean's state to the database until the end of a transaction. However, the container still flushes updates to the database before executing an EJB finder or select query if the Applicable to both container-managed persistence and bean-managed persistence beans. |
True |
|
Entity |
Causes beans returned by a Note: Applicable to container-managed persistence beans only. |
True |
|
Stateful Session |
Directory where state of passivated stateful session bean instances is stored. |
|
|
Entity |
The method called by the container to determine whether or not the bean has been modified and needs to have its changes written to the database. Applies to bean-managed persistence or EJB 1.1 container-managed persistence beans. |
If not specified, bean state is persisted after each method completes. |
This table lists the elements in weblogic-ejb-jar.xml
related to clustering. These elements control failover and load balancing behaviors for clustered beans in a WebLogic Server cluster.
Table 4-7 Clustering Elements in weblogic-ejb-jar.xml
Element | Bean Type | Description | Default |
---|---|---|---|
Stateful Session Stateless Session Entity |
Custom class to be used for routing home method calls. |
None |
|
Stateful Session Stateless Session Entity |
Indicates whether the bean home can be clustered. |
True |
|
Stateful Session Stateless Session Entity |
Algorithm to use for load-balancing among replicas of the bean home. |
Value of |
|
Stateless Session Entity |
Idempotent methods for a clustered EJB. An idempotent method can be repeated with no negative side-effects. Methods of stateless session bean homes and read-only entity bean interfaces do not need to be explicitly identified—they are automatically set to be idempotent. |
None |
|
Stateful Session |
Indicates the replication used for stateful session beans in a cluster: |
|
|
Stateless Session |
Custom class to be used for routing bean method calls. |
None |
|
Stateless Session |
Indicates that the bean is clusterable. Use only for session beans whose |
True |
|
Stateless Session |
Algorithm to use for load-balancing among replicas of the bean. |
Value of the property |
|
Stateless Session |
Causes the bean home to use server-side stubs in the server context. |
False |
This table lists the elements in weblogic-ejb-jar.xml
related to the consistency of the bean instance data and the database. These elements control behaviors such as how and when the database is updated to reflect the values in the bean instance is done.
Note:
For elements related to container-managed persistence, see Managing Entity Bean Pooling and Caching.Table 4-8 Data Consistency Elements in weblogic-ejb-jar.xml
Element | Bean Type | Description | Default |
---|---|---|---|
Entity |
How concurrent access to an entity bean is managed. |
Database |
|
Entity |
The read-only entity bean to invalidate when this container-managed persistence entity bean is modified. Note: Only applicable to EJB 2.x CMP beans. |
None |
|
Entity |
If true, the EJB container attempts to delay writing updates to a bean's state to the database until the end of a transaction. However, the container still flushes updates to the database before executing an EJB finder or select query if the Applicable to both container-managed persistence and bean-managed persistence beans. |
True |
Table 4-9 lists the elements in ejb-jar.xml
related to container-managed transactions.
Table 4-9 Container-Managed Transaction Elements in ejb-jar.xml
Element | Description | Default |
---|---|---|
|
Allowable values are |
None, EJB 2.x requires this attribute to be specified. |
|
Specifies how the container manages the transaction boundaries when delegating a method invocation to an enterprise bean's business method. Allowable values are:
Note: In in pre-9.0 releases of WebLogic Server, the EJB container would start a new transaction when no transaction existed and the value of Because clients do not provide a transaction context for calls to an MDB, MDBs that use |
If not specified, the EJB container issues a warning, and uses |
|
This optional element specifies whether an enterprise bean requires distributed transactions for its methods or whether the local transaction optimization may be used. Allowable values are |
If not specified, the container assumes that distributed transactions must be used. |
Table 4-10 lists the elements in weblogic-ejb-jar.xml
related to container-managed transactions.
Table 4-10 Container-Managed Transaction Elements in weblogic-ejb-jar.xml
Element | Description | Default |
---|---|---|
The methods for which you want the EJB container to automatically retry container-managed transactions that have rolled back. Note: Regardless of the methods specified in this element, the EJB container does not retry any transactions that fail because of system exception-based errors. |
None |
|
The transaction isolation level used when method starts a transaction. The specified transaction level is not used if the method inherits an existing transaction. |
The default of the underlying DBMS |
|
Maximum duration for a transaction. |
None |
This table lists the elements in weblogic-ejb-jar.xml
related to performance.
Table 4-11 Performance Elements in weblogic-ejb-jar.xml
Element | Bean Type | Description | Default |
---|---|---|---|
Stateful Session |
Whether multiple clients can simultaneously access a bean without triggering a The server throws a |
False |
|
Entity |
Causes the container to cache the persistent data of an entity bean between transactions. |
False |
|
Stateful Session |
Order in which stateful session beans are removed from the cache. |
NRU (not recently used) |
|
All |
Indicates that all clients of the bean are collocated with the bean on the same server instance. This element is only used if the EJB has a global JNDI name; setting it to A value of |
False |
|
Entity |
If However, the container still flushes updates to the database before executing an EJB finder or select query if the Applicable to both container-managed persistence and bean-managed persistence beans. |
True |
|
All |
Specifies the thread pool used to handle requests to the bean. |
None |
|
Entity |
The application-level entity cache, which can cache instances of multiple entity beans that are part of the same application. Note: Application level caches are declared in the |
None |
|
Entity |
Estimated average size, in bytes, of an entity bean instance. |
None |
|
Entity |
Causes beans returned by a Note: Applicable to container-managed persistence beans only. |
True |
|
Entity |
Number of seconds of inactivity after which a bean is passivated. Note: This element is not currently used. |
600 |
|
Stateful Session |
Number of seconds of inactivity after which a bean is passivated. |
600 |
|
Entity Message-Driven Stateless Session |
Number of instances of an EJB instantiated by the container at startup. |
0 |
|
Entity |
The method that changes the state of bean. Specifying this method causes WebLogic server to persist the bean state when the method completes. Note: Applies to bean-managed persistence or EJB 1.1 container-managed persistence beans. |
If not specified, bean state is persisted after each method completes. |
|
Message-driven |
The number of seconds between attempts by the EJB container to reconnect to a JMS destination that has become unavailable. |
10 |
|
Entity Stateful Session |
Maximum number of instances in the cache. |
1000 |
|
Entity Stateless Session Message-Driven |
Maximum number of instances in the free pool. |
1000 |
|
Entity |
The number of seconds between |
600 |
Container classes include the internal representation of the EJB that WebLogic Server uses and the implementation of the external interfaces (home, local, and/or remote) that clients use. You can use Oracle Workshop for WebLogic Platform or appc
to generate container classes.
Container classes are generated in according to the descriptor elements in weblogic-ejb-jar.xml
. For example, if you specify clustering elements, appc
creates cluster-aware classes that will be used for deployment. You can use appc
directly from the command line by supplying the required options and arguments. See appc for more information.
The following figure shows the container classes added to the deployment unit when the EAR or JAR file is generated.
Figure 4-2 Generating EJB Container Classes
Although infrequent, when you generate classes with appc
, you may encounter a generated class name collision which could result in a ClassCastException
and other undesirable behavior. This is because the names of the generated classes are based on three keys: the bean class name, the bean class package, and the ejb-name
for the bean. This problem occurs when you use an EAR file that contains multiple JAR files and at least two of the JAR files contain an EJB with both the same bean class, package, or classname, and both of those EJBs have the same ejb-name
in their respective JAR files. If you experience this problem, change the ejb-name
of one of the beans to make it unique.
Because the ejb-name
is one of the keys on which the file name is based and the ejb-name
must be unique within a JAR file, this problem never occurs with two EJBs in the same JAR file. Also, because each EAR file has its own classloader, this problem never occurs with two EJBs in different EAR files.
Oracle recommends that you package EJBs as part of an enterprise application. For more information, see "Deploying and Packaging from a Split Development Directory" in Developing Applications for Oracle WebLogic Server.
WebLogic Server supports the use of ejb-client.jar
files for packaging the EJB classes that a programmatic client in a different application requires to access the EJB.
Specify the name of the client JAR in the ejb-client-jar
element of the bean's ejb-jar.xml
file. When you run the appc
compiler, a JAR file with the classes required to access the EJB is generated.
Make the client JAR available to the remote client. For Web applications, put the ejb-client.jar
in the /lib
directory. For non-Web clients, include ejb-client.jar
in the client's classpath.
Note:
WebLogic Server classloading behavior varies, depending on whether the client is stand-alone. Stand-alone clients with access to theejb-client.jar
can load the necessary classes over the network. However, for security reasons, programmatic clients running in a server instance cannot load classes over the network.Deploying an EJB enables WebLogic Server to serve the components of an EJB to clients. You can deploy an EJB using one of several procedures, depending on your environment and whether or not your EJB is in production.
For general instructions on deploying WebLogic Server applications and modules, including EJBs, see Deploying Applications to Oracle WebLogic Server. For EJB-specific deployment issues and procedures, see Chapter 8, "Deployment Guidelines for Enterprise JavaBeans" in this book — Programming WebLogic Enterprise JavaBeans for Oracle WebLogic Server.
The following sections describe WebLogic Server features that are useful for checking out and debugging deployed EJBs.
If you compile your EJBs with appc
, you can use the appc -lineNumbers
command option to add line numbers to generated class files to aid in debugging. For information, see Appendix D, "appc Reference."
WebLogic Server collects a variety of data about the run-time operation of a deployed EJB. This data, which you can view in the Deployments node of the Administration Console, can be useful in determining if an EJB has completed desired processing steps. To access EJB run-time statistics, expand the Deployment node in the Administration Console, navigate to the JAR EAR that contains the bean, and select the Monitoring tab.
For information about the data available, see these pages in Oracle WebLogic Server Administration Console Help:
For instructions on how to create messages in your application to help you troubleshoot and solve bugs and problems, see Configuring Log Files and Filtering Log Messages for Oracle WebLogic Server.
This section describes Oracle tools that support the EJB development process. For a comparison of the features available in each tool, see Table 4-14.
Oracle JDeveloper is a full-featured Java IDE that can be used for end-to-end development of EJBs. For more information, see the Oracle JDeveloper online help. For information about installing JDeveloper, see Oracle Fusion Middleware Installation Guide for Oracle JDeveloper.
Oracle Enterprise Eclipse (OEPE) provides a collection of plug-ins to the Eclipse IDE platform that facilitate development of WebLogic Web services. For more information, see the Eclipse IDE platform online help.
In the Administration Console, you can view, modify, and persist to the descriptor file within the EJB a number of deployment descriptor elements. Descriptors are modified in the Administration Server copy of the EJB as well as in any deployed copies of the EJB (after deployment). When you modify descriptors, changes are made to your (the user's) original copy of the EJB (prior to deployment).
However, updating these descriptor elements takes place dynamically at runtime without requiring that the EJB be redeployed. The descriptor element that you can change in the Administration Console are limited to only those that may be dynamically changed at runtime, as summarized in Table 4-13.
The javac
compiler provided with the Java SE JDK provides java compilation capabilities. For information on javac
, see http://www.oracle.com/technetwork/java/index-jsp-142903.html#documentation
.
EJBGen is an EJB 2.x code generator. You can annotate your bean class file with javadoc tags and then use EJBGen to generate the remote and home interface classes and the deployment descriptor files for an EJB application, reducing to one the number of EJB files you need to edit and maintain.
Oracle recommends that you use EJBGen
to generate deployment descriptors; this is a Oracle best practice which allows for easier and simpler maintenance of EJBs. When you use EJBGen
, you have to write and annotate only one bean class file, which simplifies writing, debugging, and maintenance. If you use Oracle Workshop for WebLogic Platform as a development environment, Workshop automatically inserts EJBGen tags for you.
For information on EJBGen, see Appendix E, "EJBGen Reference."
DDInit is a utility for generating deployment descriptors for WebLogic Server applications. DDInit uses information from the class files to create deployment descriptor files.
See "DDInit" in Command Reference for Oracle WebLogic Server.
WebLogic Server includes Ant utilities to create skeleton deployment descriptors.
The Ant task examines a directory containing an EJB and creates deployment descriptors based on the directory contents. Because the Ant utility does not have information about all desired configurations and mappings for your EJB, the skeleton deployment descriptors the utility creates are incomplete. After the utility creates the skeleton deployment descriptors, you can use a text editor or an XML editor to edit the deployment descriptors and complete the configuration of your EJB.
For more information, see "Deploying Applications Using wldeploy" in Developing Applications for Oracle WebLogic Server.
The weblogic.Deployer
command-line tool is a Java-based deployment tool that provides a command line interface to the WebLogic Server deployment API. This tool was developed for administrators and developers who need to initiate deployment from the command line, a shell script, or any automated environment other than Java.
See "weblogic.Deployer Command-Line Reference" in Deploying Applications to Oracle WebLogic Server.
The appc
compiler generates and compiles the classes needed to deploy EJBs and JSPs to WebLogic Server. It validates the deployment descriptors for compliance with the current specifications at both the individual module level and the application level. The application-level checks include checks between the application-level deployment descriptors and the individual modules as well as validation checks across the modules.
Note:
Theappc
compiler replaces the deprecated ejbc
utility. Therefore, Oracle recommends that you use appc
instead of the deprecated ejbc
.DDConverter
is a command line tool that upgrades deployment descriptors from earlier releases of WebLogic Server. Oracle recommends that you always upgrade your deployment descriptors in order to take advantage of the features in the current Java EE specification and release of WebLogic Server.
You can use weblogic.DDConverter to upgrade your deployment descriptors. For information on using weblogic.DDConverter, see Developing Applications for Oracle WebLogic Server.
Note:
With this release of WebLogic Server, the EJB-specific DDConverter,weblogic.ejb20.utils.DDConverter
, is deprecated. Instead, use the new application-level DDConverter, weblogic.DDConverter
, to convert your application's deployment descriptors, including the EJB-specific deployment descriptors.The following table lists Oracle tools for EJB development, and the features provided by each. (Yes indicates the tool contains the corresponding feature.
Table 4-14 EJB Tools and Features
EJB Tool | Generate Interfaces and Home Interfaces | Compile Java Code | Generate Deployment Descriptors | View and Edit Deployment Descriptors | Deploy |
---|---|---|---|---|---|
WebLogic Workshop |
Yes |
Yes |
Yes |
No |
Yes |
appc |
No |
Yes |
No |
No |
No |
javac |
No |
Yes |
No |
No |
No |
EJBGen |
Yes |
No |
Yes |
Yes |
No |
DDinit |
No |
No |
Yes |
No |
No |
Administration Console |
No |
No |
No |
Yes |
Yes |
Deployer |
No |
No |
No |
No |
Yes |
DDConverter |
No |
No |
Yes |
No |
No |