|Oracle® Fusion Middleware Programming Enterprise JavaBeans for Oracle WebLogic Server
11g Release 1 (10.3.1)
Part Number E13719-01
These sections discuss design options for WebLogic Server Enterprise Java Beans (EJBs), bean behaviors to consider during the design process, and recommended design patterns.
It is assumed the reader is familiar with Java programming, EJB 2.x, and the features described in WebLogic Server Value-Added EJB Features.
After finalizing your bean design, refer to programming and other implementation topics in Chapter 4, "Implementing Enterprise Java Beans."
When you choose the bean type for a processing task, consider the different natures and capabilities of the various bean types.
Bean types vary in terms of the bean's relationship with its client. Some bean types stick with a client throughout a series of processes, serving as a sort of general contractor—acquiring and orchestrating services for the client. There are other bean types that act like subcontractors, they deliver the same single function to multiple client-oriented general contractor beans. A client-oriented bean keeps track of client interactions and other information associated with the client process, throughout a client session—a capability referred to as maintaining state. Beans that deliver commodity services to multiple client-oriented beans do not maintain state.
The following sections describe the client interaction and state management characteristics of each bean type.
Note:For a basic overview of each bean type, including an example of a business process to which each bean type is well suited, see How Do Applications Use EJBs?.
A session bean represents a single client inside the server. To access an application that is deployed on the server, the client invokes the session bean's methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.
A session bean instance has a single client. Session beans are not persistent—when the client terminates, its session bean appears to terminate and is no longer associated with the client.
A session bean can be used as a facade, between Web applications and entity beans to contain complex interactions and reduce RMI calls. When a client application accesses a remote entity bean directly, each getter method is a remote call. A session facade bean can access the entity bean locally, collect the data in a structure, and return it by value. The two types of session beans, those that maintain state and those that do not, are described in the following sections.
Stateful session beans support conversational services with tightly-coupled clients. A stateful session bean accomplishes a task for a particular client. It maintains state for the duration of a client session. After session completion, state is not retained.
Stateful session beans are instantiated on a per client basis, and can multiply and consume resources rapidly.
Like a stateful session bean, a stateless session bean performs a task for a particular client. Unlike a stateful session bean, stateless session beans do not maintain client state. A stateless session bean may maintain state only for the duration of a method invocation. When the method is finished, the state is no longer retained.
Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client request. When a home interface creates a stateless bean, it returns a replica-aware stub that can route to any server where the bean is deployed. Because a stateless bean holds no state on behalf of the client, the stub is free to route any call to any server that hosts the bean.
Because stateless session beans are never written to secondary storage, they typically offer better performance than stateful beans.
For applications that require large numbers of clients, stateless session beans offer better scalability than stateful session beans.
The system overhead of creating an instance is less for a stateless session bean than for a stateful session bean.
You can simply obtain a stateless session bean instance from the free pool.
A stateful session bean instance is instantiated upon client request, has to set the session context, and must be garbage-collected at the end of the session.
You can typically support more clients with a stateless session bean than a stateful session bean. A stateless session bean instance is only reserved for the duration of a single client request, while a stateful session bean is reserved for the duration of a session.
The number of stateless session bean instances required is usually roughly equivalent to the number of threads in the server execute queue—in the order of hundreds, while the number of stateful session bean instances required corresponds more closely to the number of clients of the application—which for some applications may be hundreds of thousands.
In this release of WebLogic Server, you can expose stateless session beans as Web Services through the Web service endpoint interface. For more information, see Oracle Fusion Middleware Getting Started With JAX-WS Web Services for Oracle WebLogic Server.
An entity bean represents a business object in a persistent storage mechanism. Some examples of business objects are customers, orders, and products. In the J2EE SDK, the persistent storage mechanism is a relational database. Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table.
These are the key features of entity beans:
Persistence—Entity bean persistence can be managed by the EJB container, or the bean itself. If a bean uses container-managed persistence, the EJB container automatically generates the necessary database access calls. The code that you write for the entity bean does not include these calls. With bean-managed persistence, you must write the database access code and include it in the bean.
Shared Access—Throughout its life cycle, an entity bean instance can support multiple clients, although not at the same time. Because the clients might want to change the same data, it is important that entity beans work within transactions. Typically, the EJB container provides transaction management. In this case, you specify the transaction attributes in the bean's
ejb-jar.xml file that control how transactions are managed. You do not have to code the transaction boundaries in the bean—the container marks the boundaries for you. For information about transaction management, see Table 3-2.
Primary Key—Each entity bean has a unique object identifier. A customer entity bean, for example, might be identified by a customer number. The unique identifier, or primary key, enables the client to locate a particular entity bean. For more information, see Using Container-Managed Relationships (CMRs).
Relationships—Like a table in a relational database, an entity bean may be related to other entity beans. You implement relationships differently for entity beans with bean-managed persistence and for those with container-managed persistence. With bean-managed persistence, the code that you write implements the relationships. But with container-managed persistence, the EJB container takes care of the relationships for you. For this reason, relationships in entity beans with container-managed persistence are often referred to as container-managed relationships. For more information, see Using Cascade Delete for Entities in CMRs.
WebLogic Server supports two types of entity beans: read-write and read-only.
Read-only beans perform better than read-write beans, because they reduce the number of times that data is read from the database.
Some applications require the use of read-write entity beans—the choice depends on frequency of updates and data consistency requirements. Table 3-1 provide key guidelines.
Table 3-1 Comparing Read-Write and Read-Only Entity Beans
|Application Requirement||Choose read-write entity beans if...||Choose read-only entity beans if...|
Frequency of updates
Your application data is updated often.
Example: A real-time stock quote feed.
Your application data is not updated often, or at all.
Example: A swimwear catalogue.
Your application requires transactionally consistent snapshots of data as it is updated.
Example: An application that updates bank account balances.
You can tolerate some level of staleness in the data: it does not have to be completely up-to-date.
Example: A news feed. Users want to see the story as soon as it is in the database, but it is not updated transactionally.
These sections describe approaches for choosing the entity bean implementation, based on your requirements for performance and data consistency.
Read-only entity beans are recommended whenever stale data is tolerable—they are suitable for product catalogs and the majority of content within many applications. Primary key-based reads are performed against a local entity cache that is invalided on a timer basis. Other queries are made against the database. Read-only entity beans perform three to four times faster than transactional entities.
Note:A client can successfully call setter methods on a read-only entity bean; however, the data will never be moved into the persistent store.
Read-write entity beans are recommended for applications that require high data consistency, for example, customer account maintenance. All reads and writes are performed against the database.
Note:For entity beans that use bean-managed persistence, or EJB 1.1 entity beans that use container-managed persistence, you can reduce the number of database writes by specifying the
For read-mostly applications, characterized by frequent reads, and occasional updates (for instance, a catalog)—a combination of read-only and read-write beans that extend the read-only beans is suitable. The read-only bean provides fast, weakly consistent reads, while the read-write bean provides strongly consistent writes.
To avoid the overhead imposed by remote calls, avoid accessing remote EJB entity beans from client or servlet code. Instead, use a session bean, referred to as a facade, to contain complex interactions and reduce calls from Web applications to RMI objects. When a client application accesses a remote entity bean directly, each getter method is a remote call. A session facade bean can access the entity bean locally, collect the data in a structure, and return it by value.
Alternatively, there are no disadvantages to accessing a local entity bean instance directly from the Web tier—it is preferable to do so than to use a facade.
Avoid the use of transfer objects, also referred to as value objects or helper classes. (A transfer object is a serializable class within an EJB that groups related attributes, forming a composite value, which is used as the return type of a remote business method.)
To optimize performance, accessing local entity instances is always preferable to the use of transfer objects.
A message-driven bean (MDB) is an enterprise bean that allows J2EE applications to process messages asynchronously. An MDB acts as a JMS or JCA message listener, which is similar to an event listener except that it receives messages instead of events. The messages may be sent by any J2EE component—an application client, another enterprise bean, or a Web component—or by non-J2EE applications.
These are the key features of message-driven beans:
Clients do not access message-driven beans through interfaces. A message-driven bean has only a bean class.
A message-driven bean's instances retain no data or conversational state for a specific client. All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance. The container can pool these instances to allow streams of messages to be processed concurrently.
Throughout its life cycle, a message-driven bean instance can process messages from multiple clients, although not concurrently.
When a message arrives, the container calls the message-driven bean's
onMessage method to process the message. The
onMessage method normally casts the message to one of the five JMS message types and handles it in accordance with the application's business logic. The
onMessage method may call helper methods, or it may invoke a session or entity bean to process the information in the message or to store it in a database.
A message may be delivered to a message-driven bean within a transaction context, so that all operations within the
onMessage method are part of a single transaction. If message processing is rolled back, the message will be re-delivered.
For information about design alternatives for message-driven beans, see MDBs and Messaging Models.
Persistence management strategy determines how an entity bean's database access is performed.
Configure the persistence management strategy—either container-managed or bean-managed—for an entity bean in the
persistence-type element in
Note:You can specify the use of a third-party persistence service for entity beans that use container-managed persistence in the
A CMP bean relies upon the EJB container for all database interaction. The bean does not contain code that accesses the database. Instead, the EJB container generates the database access methods, based on information about the entity bean's persistent fields and relationships, in
weblogic-cmp-jar.xml. For more information, see "weblogic-cmp-jar.xml Deployment Descriptor Reference".
CMP beans use EJB QL for database access. See Appendix G, "EJB Query Language (EJB-QL) and WebLogic Server."
Container-managed persistence offers these advantages:
Reduced programming effort—You do not write methods to perform database access for a CMP bean. The EJB container generates the methods automatically.
Increased portability—CMP increases bean portability in these ways:
De-coupling physical database details from business logic makes a bean logically independent of the associated database. If you implement a modified database design, or change to a different database server, you do not have to modify bean code.
You can redeploy the bean on a different J2EE application server without modifying or recompiling bean code.
Note:If you redeploy a bean that uses features that are not supported by the target application server, changes to the bean code might be necessary.
For more information on features supported by CMP entities, see Entity EJBs.
A bean that manages its own persistence must contain the methods that perform data access.
BMP is not encouraged—CMP offers many advantages over bean-managed persistence, as described in Use Container-Managed Persistence (CMP) for Productivity and Portability.
However, some application requirements cannot be satisfied by CMP beans. For instance, you must use BMP if:
Your application must use an existing library of stored SQL procedures.
The target database does not support JDBC.
There is complex mapping between the bean and database tables. For instance, the bean maps multiple tables that do not share a primary key.
A transaction is a unit of work that changes application state—whether on disk, in memory or in a database—that, once started, is completed entirely, or not at all.
Transactions can be demarcated—started, and ended with a commit or rollback—by the EJB container, by bean code, or by client code.
Transactions are costly application resources, especially database transactions, because they reserve a network connection for the duration of the transaction. In a multi-tiered architecture—with database, application server, and Web layers—you optimize performance by reducing the network traffic "round trip." The best approach is to start and stop transactions at the application server level, in the EJB container.
Container-managed transactions (CMTs) are supported by all bean types: session, entity, and message-driven. They provide good performance, and simplify development because the enterprise bean code does not include statements that begin and end the transaction.
Each method in a CMT bean can be associated with a single transaction, but does not have to be. In a container-managed transaction, the EJB container manages the transaction, including start, stop, commit, and rollback. Usually, the container starts a transaction just before a bean method starts, and commits it just before the method exits.
For information about the elements related to transaction management in
weblogic-ejb-jar.xml, see Container-Managed Transactions Elements.
If an exception is thrown during a transaction, the container will automatically roll back the transaction. You can configure the EJB container to automatically retry container-managed transactions that have rolled back, provided the transactions did not roll back as the result of system exception-based errors. You can also explicitly program rollbacks in your bean. For more information see Chapter 4, "Implementing Enterprise Java Beans."
You control how the EJB container manages the transaction boundaries when delegating a method invocation to an enterprise bean's business method for different invocation scenarios, with the
trans-attribute element in
For example, if the client calling a transaction is itself running in a transaction, the
trans-attribute element for the called transaction determines whether it will run in a new transaction or within the calling transaction.
A single database transaction can span multiple beans, on multiple servers instances. For information about implementing transactions that involve more than one bean, see Programming Transactions That Are Distributed Across EJBs.
Transactions that update multiple datastores must commit or roll back as a logical unit. The two-phase commit protocol is a method of coordinating a single transaction across multiple resource managers to ensure that updates are committed in all participating databases, or are fully rolled back out of all the databases.
Two-phase commit is resource-intensive. Avoid distributing transactions across databases.
In a bean-managed transaction, the EJB code manages the transaction, including start, stop, commit, and rollback. Bean-managed transactions are supported by all session and message-driven beans; you cannot use bean-managed transactions with entity beans.
Note:Bean-managed transactions cannot use container-provided transaction management features. Do not combine bean-managed and container-managed transactions in the same bean.
These are examples of requirements that may dictate the use of bean-managed transactions:
You need to define multiple transactions with a single method call. With container-managed transactions, a method can only be associated with a single transaction. You can use a bean-managed transaction to define multiple transactions with a single method. However, consider avoiding the need for a bean-managed transaction by breaking the method in to multiple methods, each with its own container-managed transaction.
You need to define a single transaction that spans multiple EJB method calls. For example, a stateful session EJB that uses one method to begin a transaction, and another method to commit or roll back a transaction.
Try to avoid this practice, because it requires detailed information about the workings of the EJB object. However, if this scenario is required, you must use bean-managed transaction coordination, and you must coordinate client calls to the respective methods.
To simplify development, and improve reliability, keep bean-managed transactions reasonably short.
For information about implementing bean-managed transactions, see Programming Bean-Managed Transactions.
Client applications are subject to interruptions or unexpected terminations. If you start and stop a transaction at the client level, you risk:
Consumption of network resources during waits for user actions, interruptions, until resumption of client activity or timeout.
Consumption of processing resources and network resources to rollback the transaction after timeout or termination of the transaction.
Do not manage transactions in client applications unless there are overriding reasons to do so.
A transaction's isolation level is the degree to which it exposes updated but uncommitted data to other transactions. Allowing access to uncommitted data can improve performance, but increases the risk of incorrect data being supplied to other transactions.
Set the isolation level for bean-managed transactions in the bean's Java code. For instructions, see Programming Bean-Managed Transactions.
Set the isolation level for container-managed transactions in the isolation-level sub-element of the transaction-isolation element of
weblogic-ejb-jar.xml. WebLogic Server passes this value to the underlying database. The behavior of the transaction depends both on the EJB's isolation level setting and the concurrency control of the underlying persistent store.
For more information on setting container-managed transaction isolation levels, see Oracle Fusion Middleware Programming JTA for Oracle WebLogic Server.
WebLogic Server offers a variety of value-added features for enterprise beans that you can configure to meet the requirements of your application. They are described in WebLogic Server Value-Added EJB Features.
Table 3-2 cross references requirement types with topics that describe design strategies and WebLogic Server features you can use to satisfy your application requirements.
Table 3-2 Features and Design Patterns
|When designing for...||Consider these design patterns and WebLogic Server features...|
Availability and reliability
Developer and Administrator Productivity
Choosing bean types and design patterns:
Pooling and caching: