Programming WebLogic Enterprise JavaBeans
It is assumed that the reader is familiar with Java programming and entity bean features and capabilities. For an introduction to entity beans and how they are typically used in applications, see Entity EJBs Maintain Persistent Data and Entity Bean Features.
For a description of the overall bean development process, see Implementing Enterprise Java Beans.
Figure 6-1 illustrates the lifecycle of an entity bean instance. The sections that follow describe and how the container populates and manages the free pool and the cache.
If you specify a non-zero value for the initial-beans-in-free-pool element in
weblogic-ejb-jar.xml, WebLogic Server populates the pool with the specified quantity of bean instances at startup.
The default value of
initial-beans-in-free-pool is zero. Populating the free pool at startup improves initial response time for the EJB, because initial requests for the bean can be satisfied without generating a new instance.
POOLED beans are anonymous instances, and are used for finders and home methods. The maximum number of instances the pool can contain is specified by the max-beans-in-free-pool element, in
weblogic-ejb-jar.xml which set to 1,000 by default.
A READY instance is in the cache, has an identity—an associated primary key, but is not currently enlisted in a transaction. WebLogic maintains READY entity EJB instances in least-recently-used (LRU) order.
The effect of the max-beans-in-cache element, and the quantity of instances with the same primary key allowed in the cache vary by concurrency strategy. Table 6-1 lists, for each concurrency strategy, how the value of the max-beans-in-cache element in
weblogic-ejb-jar.xml limits the number of entity bean instances in the cache, and how many entity bean instances with the same primary key are allowed in the cache.
READY entity EJB instances are removed from the cache when the space is needed for other beans. When a READY instance is removed from cache,
ejbPassivate is called on the bean, and the container will try to put it back into the free pool.
When the container tries to return an instance to the free pool and the pool already contains max-beans-in-free-pool instances, the instance is discarded.
ACTIVE entity EJB instances will not be removed from cache until the transaction they are participating in commits or rolls back, at which point they will become READY, and hence eligible for removal from the cache.
findXXX()—By default, calling a finder method on a CMP bean results in immediate load of the bean's persistent data to cache. This behavior is controlled by finders-load-bean element in the persistence stanza of
ejbLoad()—For CMP 2.0 entity beans,
ejbLoad()causes a "lazy" load of a bean's persistent data to the entity cache when the next
getXXX()for the bean's data is called. That is, when a transaction is initiated for a CMP 2.0 entity bean instance, WebLogic Server reads the bean's data from the entity cache, rather than the database, unless
ejbLoad()has been called since the bean was last loaded to cache.
Note: When used with CMP 1.1 entity beans and entity beans that use bean-managed persistence,
ejbLoad() does not perform the a lazy load—for these bean types, the bean's persistent data is loaded to cache during the
ejbStore()—WebLogic Server writes the persistent fields of an entity EJB to the database using calls to
For applications in which multiple clients can currently access and modify a bean's underlying data, the default behavior of
ejbStore() described in Understanding ejbLoad() and ejbStore() Behavior ensures database integrity by:
For instance, you might want to limit calls that access the database for performance reasons. If you application does not allow multiple transactions to concurrently access the EJB—for example, if the bean uses
Exclusive concurrency—loading the data at
ejbLoad() results in extra overhead. In such cases, you can safely reduce calls to
ejbLoad(), as described in Limiting Database Reads with cache-between-transactions (Long-Term Caching).
Alternatively, you might want to deviate from the standard
ejbStore() behavior, by calling it before a transaction commits, in order to access and use intermediate transaction results. For instructions, see Updating the Database Before Transaction Ends.
According to the EJB specification, updates made by a transaction must be reflected in the results of query-finders and
ejbSelects issued during the transaction. This requirement can slow performance. If you prefer not to flush the cache before the query is executed, you can use change the value of the include-updates element in
weblogic-cmp-jar.xml from its default value of
The decision to disable cache flushing depends on whether performance is more important than seeing the most current data. Setting
False provides the best performance but updates of the current transaction are not reflected in the query. If
True the container flushes all changes for the transactions to the database before executing the new query.
Application-level caching—also known as "combined caching"—allows multiple entity beans that are part of the same J2EE enterprise application to share a single runtime cache. There are no restrictions on the number of different entity beans that may reference an individual cache.
Application-level caching is not the best choice, however, for applications that experience high throughput. Because one thread of control exists per cache at a time, high throughput can create a bottleneck situation as tasks compete for control of the thread.
weblogic-application.xml. For a definition of this stanza and the elements it contains, see entity-cache in Developing WebLogic Server Applications.
weblogic-application.xml. A read-only entity can only use a Multiversion application-level cache. For more information, see caching-strategy in Developing WebLogic Server Applications.
weblogic-application.xml deployment descriptor is documented in the Application.xml Deployment Descriptor Elements section of Developing WebLogic Server Applications.
Every entity EJB must have a primary key that uniquely identifies an entity bean within its home. Each entity bean instance may define a different class for its primary key; multiple entity beans can use the same primary key class, as appropriate.
If two entity bean instances have the same home and the same primary key, they are considered identical. A client can invoke the
getPrimaryKey() method on the reference to an entity bean instance's remote interface to determine the instance's identity within its home.
The instance identity associated with a reference does not change during the lifetime of the reference. Therefore, the
getPrimaryKey() method always returns the same value when called on the same entity object reference. A client that knows the primary key of an entity object can obtain a reference to the entity object by invoking the
findByPrimaryKey(key) method on the bean's home interface.
In the entity bean class, you can have a primary key that maps to a single CMP field. CMP fields must be specified in both
weblogic-cmp-jar.xml. In both descriptor files, CMP fields are specified in the
cmp-field element. For simple primary keys, also specify the primary key in the
primkey-field element in the
ejb-jar.xml. In addition, specify the
prim-key-class element in
You can define your own primary key class that maps to single or multiple CMP fields. The primary key class must be
public, and have a
public constructor with no parameters. Specify the name of the primary key class in the
prim-key-class element in
ejb-jar.xml. All fields in the primary key class must be
public, and must have the same names as the corresponding
weblogic-ejb-jar.xml. For compound primary keys, which map to multiple CMP fields, do not specify
If your entity EJB uses an anonymous primary key class, you must subclass the EJB and add a
cmp-field of type
java.lang.Integer to the subclass. Enable automatic primary key generation for the field so that the container fills in field values automatically, and map the field to a database column in the
weblogic-cmp-jar.xml deployment descriptor.
ejbCreate. Instead, allow the container to create the primary key class internally, as described in Automatically Generating Primary Keys.
Integer—make the primary key class a container-managed field. Set the value of the primary key cmp-field using the
setXXXmethod within the
cmp-fieldof the type
BigDecimalas a primary key field for CMP beans. The
boolean BigDecimal.equals (object x)method considers two
BigDecimalequal only if they are equal in value and scale. This is because there are differences in precision between the Java language and different databases. For example, the method does not consider
7.10to be equal. Consequently, this method will most likely return False or cause the CMP bean to fail.
cmp-fieldis a primary key field, set the value when the
ejbCreate()method is invoked by using the
setXXXmethod for the
cmp-field. In the case, the
cmr-fieldis initialized automatically, and the
setXXXmethod for the
cmr-fieldcannot be used. Conversely, if the
cmp-fieldis not a primary key field, the
cmp-fieldis read-only. The column is updated using the
cmr-field, and the
cmp-fieldprovides a read-only view of the foreign key.
weblogic-cmp-jar.xml. Based on the values you configure, the container generates code that obtains the primary key from the database. This feature is supported for Oracle and Microsoft SQL Server databases only. In addition, see the instructions in Declaring Primary Key Field Type.
Whichever method of generated primary keys you use, see the instructions in Declaring Primary Key Field Type.
Generated primary key support for Oracle databases uses a
SEQUENCE entity in the Oracle database to generate unique primary keys. The Oracle
SEQUENCE is called when a new number is needed. Specify automatic key generation in the automatic-key-generation element in
weblogic-cmp-jar.xml. Specify the name of the Oracle
SEQUENCE in the generator-name element. If the Oracle
SEQUENCE was created with a
SEQUENCE INCREMENT, specify a key-cache-size. The value of
key-cache-size must match the value of the Oracle
SEQUENCE INCREMENT. If these two values are different, duplicate keys can result.
USER_DESIGNATED_TABLEwith Oracle. Doing so sets the
TX ISOLATION LEVELto
SERIALIZABLE,which can cause the following exception:
javax.ejb.EJBException: nested exception is: java.sql.SQLException: Automatic Key Generation Error: attempted to UPDATE or QUERY NAMED SEQUENCE TABLE NamedSequenceTable, but encountered SQLException java.sql.SQLException: ORA-08177: can't serialize access for this transaction.
SEQUENCEschema object. If you migrate an application that uses synonyms for
SEQUENCEs from a previous version of WebLogic Server to WebLogic Server 8.1, the following errors result:
Generated primary key support for Microsoft SQL Server databases uses SQL Server's
IDENTITY column. When the bean is created and a new row is inserted in the database table, SQL Server automatically inserts the next primary key value into the column that was specified as an
A sequence table is a database-neutral way to generate primary keys. The sequence table holds a monotonically increasing integer sequence value that is used as the primary key value in bean instances as they are created.
To use this feature, make sure that the underlying database supports a transaction isolation level of
Serializable value indicates that simultaneously executing a transaction multiple times has the same effect as executing the transaction multiple times in a serial fashion. This is important in a WebLogic Server cluster, in which multiple servers instances access the sequence table concurrently. See your database documentation to determine the isolation levels it supports.
Specify automatic key generation in the
weblogic-cmp-jar.xml file, as shown below. In addition, see the instructions in Declaring Primary Key Field Type.
Specify the size of the key cache— how many keys the container will fetch in a single DBMS call—in the
key-cache-size element. BEA recommends a
key-cache-size greater than one. This setting reduces the number of calls to the database to fetch the next key value.
For both native DBMS primary key generation, or key generation using a named sequence table, in the abstract
set methods of the associated entity bean, declare the primary field type to be either:
weblogic-cmp-jar.xml, set the key-cache-size element to specify how many primary key values in the sequence should be fetched from the database at a time. For example, setting
key_cache_size to 10 results in one database access for every 10 beans created, to update the sequence. The default value of
1. BEA recommends that you set
key_cache_size to a value greater than one, to minimize database accesses and to improve performance.
SEQUENCE can use a specified "increment value", which is the value by which the integer is incremented on each subsequent generation. For example, if a
SEQUENCE generates the integer 24 and the increment value is 10, then the next integer the
SEQUENCE generates will be 34.
A CMP bean can be mapped to one or more database tables. When a CMP bean is mapped to multiple tables, each table contains a row that corresponds to a particular bean instance. So, each table to which a bean maps will have the same number of rows at any point in time, and contain the same set of homogeneous primary key values. Consequently, each table must have the same number of primary key columns, and corresponding primary key columns in different tables must have the same type, though they may have different names. Tables that map to the same bean must not have referential integrity constraints declared between their primary keys. If they do, removal of a bean instance can result in a runtime error.
You map the cmp-fields of a bean to the columns of a table using the table-map element in
weblogic-cmp-jar.xml, specifying one
table-map stanza for each database table to which the bean maps. Each
table-map element maps the primary key column(s) of the table to the primary key field(s) of the bean. Non-primary key fields may only be mapped to a single table.
<!--Note `name'is the primary key field of this EJB -->
<!--Note `name'is the primary key field of this EJB -->
To make iterative development easier, the WebLogic Server EJB container can be configured to automatically change the underlying table schema as entity beans change, ensuring that tables always reflect the most recent object relationship mapping.
Note: This feature is disabled when a server instance is running in production mode, as a production environment may require the use of more precise table schema definitions, for To ensure that the container only changes tables it created, container-created tables include an extra column, called
For each CMP bean in the
Enable this feature using the
weblogic-cmp-jar.xml. The behavior of this feature varies according to the value of the element, as described in the following table. The EJB container actions described in the table occur during deployment.
You cannot set a
cmr-field until the primary key value for the bean—which is set when
ejbPostCreate is called—is available. Hence, you cannot set a
ejbPostCreate. This factor in combination with other conditions can lead to these problems:
When a related bean is created, the database insert for that bean happens before the create call finishes. If the database row for the related bean contains a foreign key that refers to the current bean and the foreign key has a referential integrity constraint defined, the insert will fail if the current bean's database row has not been inserted yet.
Note: In a one-to-one relationship, if the parent bean's primary key is embedded in the child bean's CMR field, when the EJB container creates the beans, it will not check if the parent bean has children, for performance reasons. To avoid a
duplicationKeyException database exception, you must set the foreign key constraint on the child table in the database.
You can delay database inserts until the end of the
EJBCreate method or
EJBPostCreate method, using the delay-database-insert-until element in
weblogic-cmp-jar.xml. To batch, order, and perform updates at the end of the transaction, set both enable-batch-operations and order-database-operations in
weblogic-cmp-jar.xml to "
If you choose to delay database updates for a transaction that updates related beans, you must define the relationship between the beans in the weblogic-rdbms-relation of
weblogic-cmp-jar.xml. Otherwise, database constraint errors may result when the EJB container attempts to perform the updates.
As described in Understanding ejbLoad() and ejbStore() Behavior, by default, WebLogic Server calls
ejbLoad() each time a transaction is initiated for an entity bean.
If you wish, you can configure WebLogic Server to call
ejbLoad() only when a client first references the bean or when a transaction is rolled back. This behavior is referred to as long-term caching. You enable long-term caching by setting the
cache-between-transactions element in
ReadOnlybean, WebLogic Server ignores the value of the
cache-between-transactions. WebLogic Server always performs long-term caching of read-only data, regardless of the value of
Exclusivebean, the EJB container must have exclusive update access to the underlying data: the data must not be updated by another application outside of the EJB container.
Note: If a bean with
Exclusive concurrency is deployed in a cluster long-term caching is automatically disabled because any server instance in the cluster may update the bean data. This would make caching between transactions impossible.
Optimisticbean, the EJB container reuses cached data for each transaction after the client first references the bean, but ensures that updates are transactionally consistent by checking for optimistic conflicts at the end of each transaction.
Table 6-3 lists the allowable values for the
cache-between-transactions element by entity bean type and concurrency strategy.
As described in Understanding ejbLoad() and ejbStore() Behavior, by default, WebLogic Server calls
ejbStore() only when the transaction commits.
To make intermediate results of uncommitted transactions available to other database users, set delay-updates-until-end-of-tx in the persistence element of
False—this causes WebLogic Server to call
ejbStore() after each method call.
method-permissionelement in the
ejb-jar.xmldeployment descriptor file.
WebLogic Server maps BLOBs to a cmp-field that has a byte array or serializable type. At this time, no support is available for mapping
char arrays to a CLOB column.
dbms-column-typedeployment descriptor in the
The following XML code shows how to specify a BLOB object using the dbms-column-type element in
Prior to WebLogic Server 8.1 SP02, by default, cmp-fields of type byte mapped to an OracleBlob were serialized. In WebLogic Server 8.1 SP02, by default, they are not.
To cause WebLogic Server to serialize cmp-fields of type byte mapped to an OracleBlob, set the serialize-byte-array-to-oracle-blob compatibility flag, which was introduced in WebLogic Server 8.1 SP02.
The following XML code shows how to specify a CLOB object using the dbms-column element in
The Oracle 9i and 10g drivers have different requirements for successful insertion of CLOB column values into database rows. The Oracle 9i driver requires that a database row is locked before a CLOB value can be inserted into it. As a result, on Oracle 9i, WebLogic Server does the following to insert a row that contains a CLOB column value into a table:
While these steps are necessary for successful insertion of a row that contains a CLOB column value on Oracle 9i, the steps cause an unnecessary performance hit on Oracle 10g. The Oracle 10g driver features improved handling of CLOBS and does not require a lock on a row before a CLOB column value can be inserted into it. On Oracle 10g, WebLogic Server uses a single INSERT statement to insert a row with a CLOB column value into a table, which results in increased performance of CMP EJBs.
To make use of this WebLogic Server optimization for Oracle 10g, you do not need to configure anything additional. Simply specify Oracle as your database and WebLogic Server checks to see if your Oracle version is Oracle 9i or Oracle 10g. If WebLogic Server identifies your database as Oracle 10g, rows containing CLOB values are inserted into tables in single
INSERT statements. If WebLogic Server identifies your database as Oracle 9i, rows containing CLOB values are inserted into tables in three steps as previously described.
For more information, see Handling CLOBs - Made easy with Oracle JDBC 10g and Oracle product documentation.
A field group represents a subset of a bean's container-managed persistence (CMP) and container-managed relationship (CMR) fields. To improve performance, you can put related fields in a bean into groups that are faulted into memory together as a unit.
You can associate a group with a query or relationship, so that when a bean is loaded as the result of executing a query or following a relationship, only the fields mentioned in the group are loaded.
A special group named "default" is used for queries and relationships that have no group specified. By default, the default group contains all of a bean's CMP fields and any CMR fields that add a foreign key to the bean's table.
Multiple instances of the same container-managed persistence (CMP) entity bean are often changed in a single transaction. If the EJB container issues SQL for every CMP entity bean instance, updates can become a performance bottleneck.
The EJB batch operations features solves this problem by updating multiple entries in a database table in one batch of SQL statements. This can dramatically improve performance by doing multiple database inserts, deletes, or updates for CMP beans in one database round-trip.
To enable the EJB container to correctly order database operations for related beans, you must specify the relationship between the beans, in the weblogic-rdbms-relation of
weblogic-cmp-jar.xml. Otherwise, database constraint errors may result when the EJB container attempts to perform the updates.
Batch operations only work with drivers that support the
executeBatch() methods. If the EJB container detects unsupported drivers, it reports that batch operations are not supported and disables batch operations.
sqlServer. If you have enabled automatic primary key generation with either of these types, WebLogic Server automatically disables batch operations and issues a warning.
OracleClob, batch operation automatically turns off because you will not save much time if a Blob or Clob column exist in the database table. In this case, WebLogic Server performs one insert per bean, which is the default behavior.
Container-managed relationships (CMRs) are relationships that you define between two entity EJBs, analogous to the relationships between the tables in a database. If you define a CMR between two EJBs that are involved in the same processing task, your application can benefit from these features:
The sections that follow describe the features and limitations of WebLogic Server CMRs. For instruction on configuring CMRs, see Defining Container-Managed Relationships (CMRs).
You can define a relationship between two WebLogic Server entity beans that will be packaged in the same JAR and whose data persist in the same database. Entities that participate in the same relationship must map to the same datasource. WebLogic Servers does not support relationships between entity beans that are mapped to different datasources. The abstract schema for each bean that participates in a container-managed relationship must be defined in the same
Because this feature is not specified in EJB 2.1, entity beans that have only remote interfaces, and either participate in bidirectional relationships or are the target of a unidirectional relationship, may not be portable to other application servers.
Any CMR, whether one-to-one, one-to-many, or many-to-many, can be either unidirectional or bidirectional. The direction of a CMR determines whether the bean on one side of the relationship can be accessed by the bean on the other side.
Unidirectional CMRs can be navigated in one direction only—the "dependent" bean" is unaware of the other bean in the relationship. CMR-related features such as cascade deletes can only be applied to the dependent bean. For example, if cascade deletes have been configured for a unidirectional CMR from to
EJB1 will cause deletion of
EJB2, but deleting
EJB2 will not cause deletion of
Note: For the cascade delete feature, the cardinality of the relationship is a factor—cascade deletes are not supported from the many side of a relationship, even if the relationship is bidirectional.
Bidirectional relationships can be navigated in both directions—each bean in the relationship is aware of the other. CMR-related features are supported in both directions. For example, if cascade deletes have been configured for a bidirectional CMR between
EJB2, deleting either bean in the CMR will cause deletion of the other bean.
When a bean instance that participates in a relationship is removed, the container automatically removes the relationship. For instance, given a relationship between an employee and a department, if the employee is removed, the container removes the relationship between the employee and the department as well.
Defining a CMR involves specifying the relationship and its cardinality and direction in
ejb-jar.xml. You define database mapping details for the relationship and enable relationship caching in
weblogic-cmp-jar.xml. These sections provide instructions:
Container-managed relationships are defined in the
ejb-relation stanza of
ejb-jar.xml. Listing 6-4 shows the
ejb-relation stanza for a relationship between two entity EJBs:
In Listing 6-5, the cardinality of the
TeacherEJB-StudentEJB relationship is one-to-many—it is specified by setting
one on the
TeacherEJB side and
Many on the
The cardinality of the CMR in Listing 6-5, is one-to-one—the
multiplicity is set to
one in both role stanza for the relationship
cmr-field-type would depend on the cardinality of the other side of a relationship. If the other side of a relationship has a
cmr-field> is a collection, and you must specify
java.util.Collection, as shown in the
TeacherEJB side of the relationship in Listing 6-4. If the other side has a
1, then the
cmr-field type would be single valued object. It is not necessary to specify the
-type when the
cmr-field is a single valued object.
Table 6-4 lists the contents of
cmr-field for each bean in a relationship, based on the cardinality of the relationship.
A bidirectional CMR has a
cmr-field element in the
ejb-relationship-role stanza for both sides of the relationship, as shown in Figure 6-4.
A unidirectional relationship has a
cmr-field in only one of the role stanzas for the relationship. The
ejb-relationship-role for the starting EJB contains a
cmr-field, but the role stanza for the target bean does not. Figure 6-5 specifies a unidirectional relationship from
StudentEJB— there is no
cmr-field element in the
ejb-relationship-role stanza for
Each CMR defined in
ejb-jar.xml must also be defined in a weblogic-rdbms-relation stanza in
weblogic-rdbms-relation identifies the relationship, and contains the relationship-role-map stanza, which maps the database-level relationship between the participants in the relationship, for one or both sides of the relationship.
The relation-name in
weblogic-rdbms-relation must be the same as the
ejb-relation-name for the CMR in
For one-to-one and one-to-many relationships, relationship-role-map is defined for only one side of the relationship.
For one-to-many relationships, the mapping is also always from a foreign key in one bean to the primary key of another. In a one-to-many relationship, the foreign key is always associated with the bean that is on the many side of the relationship.
For many-to-many relationships, specify a weblogic-relationship-role stanza for each side of the relationship. The mapping involves a join table. Each row in the join table contains two foreign keys that map to the primary keys of the entities involved in the relationship. The direction of a relationship does not affect how you specify the database mapping for the relationship.
FRIENDS join table has two columns,
second-friend-id. Each column contains a foreign key that designates a particular employee who is a friend of another employee. The primary key column of the employee table is
id. The example assumes that the employee bean is mapped to a single table. If employee bean is mapped to multiple tables, then the table containing the primary key column must be specified in the
relation-role-map. For an example, see Specifying CMRs for EJBs that Map to Multiple Tables.
The foreign key columns for the relationship,
Fk_column_2, are located in
Fk_BeanTable_2. The bean on the primary key side,
Pk_Bean, is mapped to a single table with primary-key columns
set...()and the text following
get.../set...must match the name of the relation field as it is declared in the
To allow remote clients to use CMR field accessor methods, put the getter and/or setter method signatures in the remote interface. However, CMR fields of a Collection datatype cannot be exposed in the remote interface. A CMR field that is a Collection can only be accessed by local methods.
When a cascade delete is performed, the deletion of a bean instance that participates in a relationship with another bean instance causes the container to also automatically delete all of the dependent bean instances. This feature is an efficient way to maintain data integrity.
ejb-jar.xml, as shown in the following example:
db-cascade-deleteis enabled, the underlying database must be set up for cascade deletes. For instructions and examples of setting up database cascade delete in WebLogic and Oracle, db-cascade-delete.
In a high volume transaction environment, transactions that use exclusive concurrency can encounter deadlocks when a transaction that performs a cascade delete needs access to the same entity bean as a transaction that does not perform a cascade delete. For information on how to avoid such deadlocks, see Preventing Deadlocks for Transactions That Use Exclusive Concurrency and Cascade Deletes.
Relationship caching—also known as "pre-fetching" or "eager relationship caching'—improves the performance of entity beans by loading related beans into the cache and preventing multiple queries by issuing a join query for the related bean. If a set of beans are accessed as part of the same unit of work, then your application should load them into cache at the same time.
Without relationship caching, an SQL query is issued by the first line of code to load the
accountBean and another SQL query is issued by the second line of code to load the
addressBean; this results in two queries to the database.
With relationship caching, a single query is issued to load both
addressBean by the first line of code, which should result in better performance. So, if you know that a related bean will be accessed after executing a particular finder method, it is a good idea to let the finder method know via the relationship caching feature.
If you enable relationship caching for a finder or a select method, the result of the query will always be a distinct set even if the
distinct keyword is not specified. This is due to a technical limitation that does not allow the EJB container to distinguish duplicates in the underlying JDBC result set.
With relationship caching enabled, changes to the relationship are automatically reflected in cache. For instance, if a instance is added on the "many" side of a one-to-many relationship, that change is reflected in the cached relationship—a subsequent query to the bean on the "one" side of the relationship causes the relationship to be refreshed in cache, so that the new instance is available to the query.
caching-name element is specified in the
weblogic-query stanza, when the finder query is executed, WebLogic Server loads data for related beans as specified by the relationship-caching element that the
caching-name element specifies.
weblogic-ejb-jar.xml) for the bean that contains the finder is not set to
Falseor relationship caching will not be enabled. The default value of
weblogic-cmp-jar.xmlfile. Relationship caching uses outer joins for queries and outer join syntax can vary by database type.
Because relationship caching uses join queries, the number of
caching-element stanzas in the
relationship-caching element can increase duplicates in the result set. Specify one one-to-many relationships per
caching-element to avoid duplicates in the result set.
caching-element elements enables the bean to load more than one level of related beans. In the above sample,
addressBean is the second level related bean because it is nested in the
accountBean. Currently, there is no limitation on the number of
caching-elements that you can specify. However, setting too many
caching-element levels could have an impact on the performance of the current transaction.
An entity bean's concurrency strategy specifies how the EJB container should manage concurrent access to the bean; it determines how and when WebLogic Server synchronizes its cached copy of the entity with the database.
With exclusive concurrency, the container places an exclusive lock on cached EJB instances when the bean is associated with a transaction. Other requests for the EJB instance are blocked until the transaction completes. Exclusive locks are local to the server instance, so this strategy is most appropriate for a single server architecture. When used in a cluster, exclusive concurrency serializes all requests to a bean instance within a server instance, but concurrency between servers in the cluster that access the same bean concurrently is governed by the database.
Multiple clients can use the exclusive concurrency option to access entity EJBs in a serial fashion. Using this exclusive option means that if two clients simultaneously attempt to access the same entity EJB instance (an instance having the same primary key), the second client is blocked until the EJB is available.
With database concurrency, concurrency control for an EJB for each transaction is deferred to the underlying datastore. WebLogic Server allocates a separate entity bean instance to each transaction and allows concurrency control to be handled by the database. This is the default option.
Database mechanism, the EJB container continues to cache instances of entity bean instances. However, the container does not cache the intermediate state of a bean instance between transactions. Instead, WebLogic Server issues a SQL
SELECT for each instance at the beginning of a transaction to obtain the latest EJB data. A SQL
UPDATE is issued if there are changes.
As with the
Database concurrency strategy,
Optimistic concurrency gives each transaction its own bean instance. The
Optimistic concurrency strategy does not hold any locks in the EJB container or the database while the transaction is in process.
Note: For databases that do read-locking (non-Oracle databases) optimistic beans read data in a separate, local transaction. The local transaction commits a soon as the read completes. This strategy avoids read locks and can allow for better scalability when transactions do not update the same data concurrently.
You can configure the EJB container to validate an Optimistic bean's transaction data before committing the transaction, to verify that no data read or updated by the transaction has bean changed by another transaction. If it detects changed data, the EJB container rolls back the transaction.
The verify-columns element specifies how columns in a table are checked for validity when you use the optimistic concurrency strategy.
Read—To check all columns in the table that have been read during the transaction. This includes both rows that are simply read and rows that are read and then updated or deleted by the transaction.
Modified—To check only the columns that have been updated or deleted by the current transaction.
Version—To check that a version column exists in the table and that this column is used to implement optimistic concurrency.
Timestamp—To check that a timestamp column exists in the table and that this column is used to implement optimistic concurrency. Timestamp-based optimistic concurrency requires a 1 second granularity for the database column.
Note: The version or timestamp column is not updated if the transaction did not modify any regular CMP or CMR fields—if the only data changed during the transaction was the value of the version or timestamp column (as a result of transaction initiation) the column used for optimistic checking will not be updated at the end of the transaction.
Read—To check all rows in the table that have been read during the transaction. This includes both rows that are simply read and rows that are read and then updated or deleted by the transaction. Checking all rows entails additional overhead because it generally increases the amount of optimistic checking that must be performed by the EJB container. With the
Readoption, committed transactions read a set of rows that are guaranteed not to be modified by another transaction until after the transaction commits. This results in a high level of consistency which is very close to the ANSI definition of SERIALIZABLE consistency.
Modified—To check only the rows that have been updated or deleted by the current transaction. This setting ensures that two transactions will not update the same row concurrently, resulting in a lost update, but it allows reads and updates of different transactions to be interleaved. This results in a level of consistency that falls between the ANSI READ_COMMITTED and REPEATABLE_READ levels of consistency.
verify-columnsis set to
Timestamp, specify the version or timestamp column using the optimistic-column in the table-map stanza in the
weblogic-cmp-jar.xmlfile. Mapping this column to a cmp-field is optional.
optimistic-column element identifies a database column that contains a version or timestamp value used to implement optimistic concurrency. This element is case maintaining, though not all databases are case sensitive. The value of this element is ignored unless
verify-columns is set to
For Oracle databases, if you set
Modified for an entity EJB with a CMP non-key field type
java.util.Date and implementation type Oracle
DATE, WebLogic Server throws an optimistic concurrency violation exception when a simple update is made to the non-key
DATE field—even though only one user is updating the record.
This problem occurs because of a mismatch in date value precision between the Oracle
DATE column and the
java.util.Date type. The
java.util.Date type is in milliseconds, and the Oracle
DATE column is not. There are two ways to avoid this error:
Timestamp, a higher precision type introduced in Oracle9i.
java.util.Datevalue. To accomplish this, prepare a date field for an entity bean
java.util.Datefield in this way:
Used to signify that a bean is read-only. The container activates a new bean instance for each transaction so that requests proceed in parallel. WebLogic Server calls
ejbLoad() for read-only beans based on the read-timeout-seconds parameter.
Prior to version WebLogic Server 8.1 SP02, EJBs that used ReadOnly concurrency were allowed to use create and remove operations. In WebLogic Server 8.1 SP02, create and remove operations are not allowed for EJBs that used ReadOnly concurrency, because this practice is discouraged, and to allow generation of more efficient code for read-only beans.
To support the pre-SP02 behavior and allow read-only beans to use create and remove operations, set the allow-readonly-create-and-remove element in
Concurrency strategies present a trade-off between performance and freshness of data. You should choose a concurrency strategy based on which of these factors weighs more heavily in your application. The trade-offs are summarized in Table 6-5.
Mitigate deadlock risk by setting use-select-for-update in
Note: Use the transaction-isolation element in combination with Database concurrency to achieve the desired concurrency behavior.
Serializes access to EJB data in a single server (non-clustered environment) for a high level of consistency. Avoids deadlocks due to lock upgrades, and prevents unnecessary calls to
Note: Using Entity Beans with parameter settings concurrency-strategy=Exclusive and use-select-for-update=true together may cause a temporary deadlock. Avoid using these parameter settings in conjunction or set the parameter cache-between-transaction=true.
Specify the concurrency mechanism for a bean by setting the
concurrency-strategy element in the entity-cache stanza in
concurrency-strategy is defined at the bean level, different beans in the same application can use different concurrency strategies, as appropriate.
In situations of high throughput, transactions that use an exclusive concurrency strategy can encounter deadlocks if a transaction that performs a cascade delete needs access to the same entity bean as a transaction that does not perform a cascade delete.
You can prevent such deadlocks with the lock-order element of
weblogic-cmp-jar.xml deployment descriptor file.
lock-order defines the order in which beans are locked during a cascade delete of related beans. Its value is an integer value. The bean with the lowest
lock-order value is processed first, the bean with the next lowest
lock-order value is processed next, and so on.
lock-order causes a cascade delete to lock bean instances in the same order as their other transactions. If the normal lock order is BeanA, then BeanB, specify this
lock-order, and cascade delete will use it.
For persistent data that is only occasionally updated, you can implement a "read-mostly pattern" in WebLogic Server by mapping a read-only and a read-write entity bean to the same data. You use the read-only entity bean for reads and the read-write entity bean for writes.
The read-only entity EJB loads bean data at intervals specified by the
read-timeout-seconds element in the
entity-cache-ref) stanza for the bean in
weblogic-ejb-jar.xml. To ensure that the read-only bean always returns current data, the read-only bean must be must invalidated when the read-write bean changes the entity bean data. You can configure WebLogic Server to automatically invalidate the read-only bean, or explicitly invalidate it in bean code, as described in Invalidating Read-Only Entity EJBs Implicitly and Invalidating Read-Only Entity EJBs Explicitly respectively.
In a WebLogic Server cluster, the read-mostly pattern gives clients of the read-only EJB the performance advantage of reading from cache, while clients of read-write EJB enjoy true transactional behavior—the
read-write EJB's cached state always matches the persistent data in the database.
read-timeout-secondssetting for its read-only counterparts.
If you are running EJB 2.0, you can approximate the read-mostly pattern using a single bean that uses optimistic concurrency. An optimistic bean acts like a read-only beans when performing a read—it reads from the cache and can return stale data. However, when an optimistic bean performs a write, the container ensures that the data being updated has not changed—providing the same level of consistency for writes as a bean that uses Database concurrency. See Choosing a Concurrency Strategy.
The invalidation-target element in the
entity-descriptor stanza in
weblogic-ejb-jar.xml identifies a read-only entity EJB that should be invalidated when a CMP entity bean has been modified.
invalidation-target may only be specified for an EJB 2.0 CMP entity bean. The target ejb-name must be a read-only entity EJB.
invalidate() method causes the read-only entity beans to be invalidated in the local server instance. If the server instance is a member of a cluster, it multicasts a message to the other clustered servers to invalidate their cached copies of the bean. Upon the next
getXXX() to an invalidated read-only entity bean, the container loads the current version of the bean's persistent data to the entity cache from the database, as described in Understanding ejbLoad() and ejbStore() Behavior.
WebLogic Server calls
invalidate() after the update transaction update has completed. If the invalidation occurs during a transaction update, the previous version might be read if the
isolation-level for transactions does not permit reading uncommitted data.
The following sections are a quick reference to WebLogic Server-specific deployment for CMP entity beans. Each section contains the elements related to a particular the type of feature or behavior. The table in each section defines relevant elements terms of: the behavior it controls, the parent stanza in
weblogic-cmp-jar.xml that contains the element, and the behavior you can expect if you do not explicitly specify the element in
For a m:m relationship, specify the roles on both sides of the relationship. roles for both sides of the relationship are specified. For an example, see Defining a Many-to-Many Relationship.