BEA Logo BEA WebLogic Server Release 6.1

  BEA Home  |  Events  |  Solutions  |  Partners  |  Products  |  Services  |  Download  |  Developer Center  |  WebSUPPORT

 

  |  

  WebLogic Server Doc Home   |     Programming WebLogic EJB   |   Previous Topic   |   Next Topic   |   Contents   |   View as PDF

WebLogic Server Container-Managed Persistence Services

 

The following sections describe the new container-managed persistence (CMP) services available with the WebLogic Server EJB container.

 


Overview of Container Managed Persistence Services

WebLogic Server's container is responsible for providing a uniform interface between the EJB and the server. The container creates new instances of the EJBs, manages these bean resources, and provides persistent services such as, transactions, security, concurrency, and naming at runtime. In most cases, pre WebLogic Server 6.1 EJBs run in the container. However, see the Migration Guide for information on when you would need to migrate your bean code. See DDConverter for instructions on using the conversion tool.

WebLogic Server's container-managed persistence (CMP) model handles persistence of CMP entity beans automatically at runtime by synchronizing the EJB's instance fields with the data in the database.

EJB Persistence Services

WebLogic Server provides persistence services for entity beans. An entity EJB can save its state in any transactional or non-transactional persistent storage ("bean-managed persistence"), or the container can save the EJB's non-transient instance variables automatically ("container-managed persistence"). WebLogic Server allows both choices and a mixture of the two.

If an EJB will use container-managed persistence, you specify the type of persistence services that the EJB uses in the weblogic-ejb-jar.xml deployment file. High-level definitions for automatic persistence services are stored in the persistence-type and persistence-use elements. The persistence-type element defines one or more automatic services that the EJB can use. The persistence-use element defines which service the EJB uses at deployment time.

Automatic persistence services use additional deployment files to specify their deployment descriptors, and to define entity EJB finder methods. For example, WebLogic Server RDBMS-based persistence services obtain deployment descriptors and finder definitions from a particular bean using the bean's weblogic-cmp-rdbms-jar.xml file, described in Using WebLogic Server RDBMS Persistence.

Third-party persistence services cause other file formats to configure deployment descriptors. However, regardless of the file type, you must reference the configuration file in the persistence-type and persistence-use elements in weblogic-ejb-jar.xml.

Note: Configure container-managed persistence beans with a connection pool with maximum connections greater than 1. WebLogic Server's container-managed persistence service sometimes needs to get two connections simultaneously.

Using WebLogic Server RDBMS Persistence

To use WebLogic Server RDBMS-based persistence service with your EJBs, create a dedicated XML deployment file and define the persistence elements for each EJB that will use container-managed persistence. If you use WebLogic Server's utility, DDConverter to create this file, it is named weblogic-cmp-rdbms-jar.xml. If you create the file from scratch, you can save it to a different filename. However, you must ensure that the persistence-type and persistence-use elements in weblogic-ejb-jar.xml refer to the correct file.

weblogic-cmp-rdbms-jar.xml defines the persistence deployment descriptors for EJBs using WebLogic Server RDBMS-based persistence services.

In each weblogic-cmp-rdbms-jar.xml file you define the following persistence options:

 


Writing for RDBMS Persistence for EJB 1.1 CMP

Clients use finder methods to query and receive references to entity beans that fulfill query conditions. This section describes how to write finders for WebLogic-specific 1.1 EJBs that use RDBMS persistence. EJB QL, a portable query language, is used to define finder queries for 2.0 EJBs with container-managed persistence. For more information about on EJB QL, see Using EJB QL for EJB 2.0.

WebLogic Server provides an easy way to write finders. The EJB provider writes the method signature of a finder in the EJBHome interface, and defines the finder's query expressions in the ejb-jar.xml deployment file.

ejbc creates implementations of the finder methods at deployment time, using the queries in ejb-jar.xml.

The key components of a finder for RDBMS persistence are:

The following sections explain how to write EJB finders using XML elements in WebLogic Server deployment files.

Finder Signature

EJB providers specify finder method signatures using the form findMethodName(). Finder methods defined in weblogic-cmp-rdbms-jar.xml must return a Java collection of EJB objects or a single object.

Note: EJB providers can also define a findByPrimaryKey(primkey) method that returns a single object of the associated EJB class.

finder-list Stanza

The finder-list stanza associates one or more finder method signatures in EJBHome with the queries used to retrieve EJB objects. The following is an example of a simple finder-list stanza using WebLogic Server RDBMS-based persistence:

<finder-list>
      <finder>
              <method-name>findBigAccounts</method-name>
              <method-params>
                    <method-param>double</method-param>
                </method-params>
                <finder-query><![CDATA[(> balance $0)]]>
            </finder-query>
      </finder>
</finder-list>

Note: If you use a non-primitive data type in a method-param element, you must specify a fully qualified name. For example, use java.sql.Timestamp rather than Timestamp. If you do not use a qualified name, ejbc generates an error message when you compile the deployment unit.

finder-query Element

The finder-query element defines the WebLogic Query Language (WLQL) expression used to query EJB objects from the RDBMS. WLQL uses a standard set of operators against finder parameters, EJB attributes, and Java language expressions. See Using WebLogic Query Language (WLQL) for EJB 1.1 CMP for more information on WLQL.

Note: Always define the text of the finder-query value using the XML CDATA attribute. Using CDATA ensures that any special characters in the WLQL string do not cause errors when the finder is compiled.

A CMP finder can load all beans using a single database query. So, 100 beans can be loaded with a single database round trip. A bean-managed persistence (BMP) finder must do one database round trip to get the primary key values of the beans selected by the finder. As each bean is accessed, another database access is also typically required, assuming the bean wasn't already cached. So, to access 100 beans, a BMP might do 101 database accesses.

 


Using WebLogic Query Language (WLQL) for EJB 1.1 CMP

WebLogic Query Language (WLQL) for EJB 1.1 CMP allows you to query 1.1 entity EJBs with container-managed persistence. In the weblogic-cmp-rdbms-jar.xml file, each finder-query stanza must include a WLQL string that defines the query used to return EJBs. Use WLQL for EJBs and their corresponding deployment files that are based on the EJB 1.1 specification.

Note: For queries to 2.0 EJBs, see Using EJB QL for EJB 2.0. Using the weblogic-ql query completely overrides the ejb-ql query.

Syntax

WLQL strings use the prefix notation for comparison operators:

(operator operand1 operand2)

Additional WLQL operators accept a single operand, a text string, or a keyword.

Operators

The following are valid WLQL operators.

Operator

Description

Sample Syntax

=

Equals

(= operand1 operand2)

<

Less than

(< operand1 operand2)

>

Greater than

(> operand1 operand2)

<=

Less than or equal to

(<= operand1 operand2)

>=

Greater than or equal to

(>= operand1 operand2)

!

Boolean not

(! operand)

&

Boolean and

(& operand)

|

Boolean or

(| operand)

like

Wildcard search based on % symbol in the supplied text_string

(like text_string%)

isNull

Value of single operand is null

(isNull operand)

isNotNull

Value of single operand is not null

(isNotNull operand)

orderBy

Orders results using specified database columns

Note: Always specify a database column name in the orderBy clause, rather than a persistent field name. WebLogic Server does not translate field names specified in orderBy.

(orderBy 'column_name')

desc

Orders results in descending order. Used only in combination with orderBy.

(orderBy 'column_name desc')

Operands

Valid WLQL operands include:

Examples of WLQL Expressions

The following example code shows excerpts from the weblogic-cmp-rdbms-jar.xml file that use basic WLQL expressions.

Note: Always define the text of the finder-query value using the XML CDATA attribute. Using CDATA ensures that any special characters in the WLQL string do not cause errors when the finder is compiled.

 


Using EJB QL for EJB 2.0

EJB Query Language (QL) is a portable query language that defines finder methods for 2.0 entity EJBs with container-managed persistence. Use this SQL-like language to select one or more entity EJB objects or fields in your query. Because of the declaration of CMP fields in a deployment descriptor, you can create queries in the deployment descriptor for any finder method other than findByPrimaryKey(). findByPrimaryKey is automatically handled by the container. The search space for an EJB QL query consists of the EJB's schema as defined in ejb-jar.xml (the bean's collection of container-managed fields and their associated database columns).

EJB QL Requirement for EJB 2.0 Beans

The deployment descriptors must define each finder query for EJB 2.0 entity beans by using an EJB QL query string. You cannot use WebLogic Query Language (WLQL) with EJB 2.0 entity beans. WLQL is intended for use with EJB 1.1 CMP.

Migrating from WLQL to EJB QL

If you have used previous versions of WebLogic Server, your container-managed entity EJBs may use WLQL for finder methods. This section provides a quick reference to common WLQL operations. Use this table to map the WLQL syntax to EJB QL syntax.

Sample WLQL Syntax

Equivalent EJB QL Syntax

(= operand1 operand2)

WHERE operand1 = operand2

(< operand1 operand2)

WHERE operand1 < operand2

(> operand1 operand2)

WHERE operand1 > operand2

(<= operand1 operand2)

WHERE operand1 <= operand2

(>= operand1 operand2)

WHERE operand1 >= operand2

(! operand)

WHERE NOT operand

(& expression1 expression2)

WHERE expression1 AND expression2

(| expression1 expression2)

WHERE expression1 OR expression2

(like text_string%)

WHERE operand LIKE `text_string%'

(isNull operand)

WHERE operand IS NULL

(isNotNull operand)

WHERE operand IS NOT NULL

Using EJB 2.0 WebLogic QL Extension for EJB QL

WebLogic Server has an SQL-like language, called WebLogic QL, that extends the standard EJB QL. This language works with the finder expressions and is used to query EJB objects from the RDBMS. You define the query in the weblogic-cmp-rdbms-jar.xml deployment descriptor using the weblogic-ql element.

There must be a query element in the ejb-jar.file that corresponds to the weblogic-ql element in the weblogic-cmp-rdbms-jar.xml file. However, the weblogic-cmp-rdbms-jar.xml query element overrides the ejb-jar.xml query element.

SELECT DISTINCT

The EJB WebLogic QL extension SELECT DISTINCT tells your database to filter duplicate queries. Using SELECT DISTINCT means that the EJB container's resources are not used to sort through duplicated results when SELECT DISTINCT is specified in the EJB QL query.

If you specify a sql-select-distinct element with the value TRUE in a weblogic-ql element's XML stanza for an EJB 2.0 CMP bean, then the generated SQL STATEMENT for the database query will contain a DISTINCT clause.

You specify the sql-select-distinct element in the weblogic-cmp-rdbms-jar.xml file. However, you cannot specify sql-select-distinct if you are running an isolation level of READ_C0MMITED_FOR_UPDATE on an Oracle database. This is because a query on Oracle cannot have both a sql-select-distinct and a READ_C0MMITED_FOR_UPDATE. If there is a chance that this isolation level will be used, for example in a session bean, do not use the sql-select-distinct element.

ORDERBY

The EJB WebLogic QL extension ORDERBY is a keyword that works with the Finder method to specify the CMP field selection sequence for your selections.

Figure 5-1 WebLogic QL ORDERBY extension showing order by id.

ORDERBY
      SELECT OBJECT(A) from A for Account.Bean
            ORDERBY A.id

Note: ORDERBY defers all sorting to the DBMS. Thus, the order of the retrieved result depends on the particular DBMS installation on top of which the bean is running.

 


Using Oracle SELECT HINTS

WebLogic Server supports an EJB QL extension that allows you to pass INDEX usage hints to the Oracle Query optimizer. With this extension, you can provide a hint to the database engine. For example, if you know that the database you are searching can benefit from an ORACLE_SELECT_HINT, you can define an ORACLE_SELECT_HINT clause that will take ANY string value and then insert that String value after the SQL SELECT statement as a hint to the database.

To use this option, declare a query that uses this feature in the weblogic-ql element. This element is found in the weblogic-cmp-rdbms-jar.xml file. The weblogic-ql element specifies a query that contains a WebLogic specific extension to the EJB-QL language.

The WebLogic QL keyword and usage is as follows:

SELECT OBJECT(a) FROM BeanA AS a WHERE a.field > 2 ORDERBY a.field 
SELECT_HINT '/*+ INDEX_ASC(myindex) */'

This statement generates the following SQL with the optimizer hint for Oracle:

SELECT /*+ INDEX_ASC(myindex) */ column1 FROM .... (etc)

In the WebLogic QL ORACLE_SELECT_HINT clause, whatever is between the single quotes ( ' ' ) is what gets inserted after the SQL SELECT. It is the query writer's responsibility to make sure that the data within the quotes makes sense to the Oracle database.

 


"get" and "set" Method Restrictions

WebLogic Server uses a series of accessor methods. The names of these methods begin with set and get. WebLogic Server uses these methods to read and modify container-managed fields. These container-generated classes must begin with "get" or "set" and use the actual name of a persistent field defined in ejb-jar.xml. The methods are also declared as public, protected, and abstract.

 


BLOB and CLOB DBMS Column Support for the Oracle DBMS

WebLogic Server supports Oracle Binary Large Object (BLOB) and Character Large Object (CLOB) DBMS columns with EJB CMP. BLOBs and CLOBs are data types used for efficient storage and retrieval of large objects. CLOBs are string or char objects; BLOBs are binary or serializable objects such as pictures that translate into large byte arrays.

BLOBs and CLOBs map a string variable, a value of OracleBlob or OracleClob, to a BLOB or CLOB column. WebLogic Server maps CLOBs only to the data type java.lang.string. At this time, no support is available for mapping char arrays to a CLOB column.

To enable BLOB/CLOB support:

  1. In the bean class, declare the variable.

  2. Edit the XML by declaring the dbms-column-type deployment descriptor in the weblogic-cmp-rdbms jar.xml file.

  3. Create the BLOB or CLOB in the Oracle database.

Using BLOB or CLOB may slow performance because of the size of the BLOB or CLOB object.

Specifying a BLOB Using the Deployment Descriptor

The following XML code shows how to specify a BLOB object using the dbms-column element in weblogic-cmp-rdbms-jar-xml file.

Figure 5-2 Specifying a BLOB object

<field-map>
	<cmp-field>photo</cmp-field>
	<dbms-column>PICTURE</dbms-column>
	<dbms_column-type>OracleBlob</dbms-column-type>
</field-map>

Controlling Serialization of cmp-fields Mapped to OracleBlobs

By default, when WebLogic Server writes and reads a cmp-field of type byte[] that is mapped to an OracleBlob, it serializes and deserializes the field, respectively.

If WebLogic Server reads a BLOB that was written directly to the database by another program, errors can result, because the container assumes that the data is serialized.

To specify that the data is not serialized, compile the EJB with this flag:

java -Dweblogic.byteArrayIsSerializedToOracleBlob=false 
weblogic.ejbc std_ejb.jar ejb.jar 

Specifying a CLOB Using the Deployment Descriptors

The following XML code shows how to specify a CLOB object using the dbms-column element in the weblogic-cmp-rdbms-jar-xml file.

Figure 5-3 Specifying a CLOB object

<field-map>
	<cmp-field>description</cmp-field>
	<dbms-column>product_description</dbms-column>
	<dbms_column-type>OracleClob</dbms-column-type>
</field-map>

 


Cascade Delete

Use the cascade delete mechanism to remove entity bean objects. When cascade delete is specified for a particular relationship, the lifetime of one entity object depends on another. You can specify cascade delete for one-to-one and one-to-many relationships; many-to-many relationships are not supported. The cascade delete() method uses the delete features in WebLogic Server, and the database cascade delete() method instructs WebLogic Server to use the underlying database's built-in support for cascade delete.

To enable this feature, you must recompile the bean code for the changes to the deployment descriptors to take effect.

Use one of the following two methods to enable cascade delete.

Cascade Delete Method

With the cascade delete() method you use WebLogic Server to remove objects. If an entity is deleted and the cascade delete element is specified for a related entity bean, then the removal is cascaded and any related entity bean objects are also removed.

To specify cascade delete, use the cascade-delete element in the ejb-jar.xml deployment descriptor elements. This is the default method. Make no changes to your database settings, and WebLogic Server will cache the entity objects for removal when the cascade delete is triggered.

Specify cascade delete using the cascade-delete element in the ejb-jar.xml file as follows:

Figure 5-4 Specifying a cascade delete

<ejb-relation>
	<ejb-relation-name>Customer-Account</ejb-relation-name>
	<ejb-relationship-role>
		<ejb-relationship-role-name>Account-Has-Customer
		</ejb-relationship-role-name>
		<multiplicity>one</multiplicity>
		<cascade-delete/> 
	</ejb-relationship-role>
</ejb-relation>

Note: This cascade delete() method can only be specified for a ejb-relationship-role element contained in an ejb-relation element if the other ejb-relationship-role element in the same ejb-relation element specifies a multiplicity attribute with a value of one.

Database Cascade Delete Method

The database cascade delete() method allows an application to take advantage of a database's built-in cascade delete support, and possibly improve performance. If the db-cascade-delete element is not already specified in the weblogic-cmp-rdbms-jar.xml file, do not enable any of the database's cascade delete functionality, because this will produce incorrect results in the database.

The db-cascade-delete element in the weblogic-cmp-rdbms-jar.xml file specifies that a cascade delete operation will use the built-in cascade delete facilities of the underlying DBMS. By default, this feature is turned off and the EJB container removes the beans involved in a cascade delete by issuing an individual SQL DELETE statement for each bean.

If db-cascade-delete element is specified in the weblogic-cmp-rdbms-jar.xml, the cascade-delete element must be specified in the ejb-jar.xml.

When db-cascade-delete is enabled, additional database table setup is required. For example, the following setup for the Oracle database table will cascade delete all of the employees if the dept is deleted in the database.

Figure 5-5 Oracle table setup for cascade delete

CREATE TABLE dept
        (deptno      NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY,
          dname        VARCHAR2(9) );
CREATE TABLE emp
        (empno        NUMBER(4) PRIMARY KEY,
          ename        VARCHAR2(10),
          deptno    NUMBER(2)   CONSTRAINT fk_deptno
                          REFERENCES dept(deptno)
                          ON DELETE CASCADE );

 


Tuned EJB 1.1 CMP Updates in WebLogic Server

EJB container-managed persistence (CMP) automatically support tuned updates because the container receives get and set callbacks when container-managed EJBs are read or written. Tuning EJB 1.1 CMP beans helps improve their performance.

WebLogic Server now supports tuned updates for EJB 1.1 CMP. When ejbStore is called, the EJB container automatically determines which container-managed fields have been modified in the transaction. Only modified fields are written back to the database. If no fields are modified, no database updates occur.

With previously versions of WebLogic Server, you could to write an isModified method that notified the container whether the EJB 1.1 CMP bean had been modified. isModified is still supported in WebLogic Server, but we recommend that you no longer use isModified methods and instead allow the container to determine the update fields.

This feature is enabled for EJB 2.0 CMP, by default. To enable tuned EJB 1.1 CMP updates, make sure that you set the following deployment descriptor element in the weblogic-cmp-rdbms-jar.xml file to true.

<enable-tuned-updates>true</enable-tuned-updates>

You can disable tuned CMP updates by setting this deployment descriptor element as follows:

<enable-tuned-updates>false</enable-tuned-updates>

In this case, ejbStore always writes all fields to the database.

 


Flushing the CMP Cache

Updates made by a transaction must be reflected in the results of queries, finders, and ejbSelects issued during the transactions. Because this requirement can slow performance, a new option enables you to specify that the cache be flushed before the query for the bean is executed.

If this option is turned off, which is the default behavior, the results of the current transactions are not reflected in the query. If this option is turned on, the container flushes all changes for cached transactions written to the database before executing the new query. This way, the changes show up in the results.

To enable this option, in weblogic-cmp-rdbms-jar.xml file set the include-updates element to true.

Figure 5-6 Specifying that results of transactions be reflected in the query

<weblogic-query>
	<query-method>
	<method-name>findBigAccounts</method_name>
	<method-params>
		<method-param>double</method-param>
	</method-params>
	</query-method>
	<weblogic-ql>WHERE BALANCE>10000 ORDERBY NAME</weblogic-ql>
	<include-updates>true</include-updates>
</weblogic-query>

The default is false, which provides the best performance. Updates made to the cached transaction are reflected in the result of a query; no changes are written to the database, and you do not see the changes in the query result.

Whether you use this feature depends on whether performance is more important than current and consistent data.

 


Primary Keys

The primary key is an object that uniquely identifies an entity bean within its home. The container must be able to manipulate the primary key of an entity bean. Each entity bean class may define a different class for its primary key, but multiple entity beans can use the same primary key class. The primary key is specified in the deployment descriptor for the entity bean. You can specify a primary key class for an entity bean with container-managed persistence by mapping the primary key to either a single field or to multiple fields in the entity bean class.

Every entity object has a unique identity within its home. If two entity objects 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 object's remote interface to determine the entity object's identity within its home. The object identify associated with the 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.

Primary Key Mapped to a Single CMP Field

In the entity bean class, you can have a primary key that maps to a single CMP field. You use the primkey-field element, a deployment descriptor in the ejb-jar.xml file, to specify the container-managed field that is the primary key. The prim-key-class element must be the primary key field's class.

Primary Keys Class That Wraps Single or Multiple CMP Fields

You can have a primary key class that maps to single or multiple fields. The primary key class must be public, and have a public constructor with no parameters. You use the prim-key-class element, a deployment descriptor in the ejb-jar.xml file to specify the name of the entity bean's primary key class. You can only specify the the class name in this deployment descriptor element. All fields in the primary key class must be declared public. The fields in the class must have the same name as the primary key fields in the ejb-jar.xml file.

Hints for Using Primary Keys

Some hints for using primary keys with WebLogic Server include:

Mapping to a Database Column

WebLogic Server supports mapping a database column to a cmp-field and a cmr-field concurrently. The cmp-field is read-only in this case. If the cmp-field is a primary key field, specify that the value for the field be set when the create() method is invoked by using the setXXX method for the cmp-field.

 


Automatic Primary Key Generation for EJB 2.0 CMP

WebLogic Server supports an automatic primary key generation feature for container-managed persistence (CMP).

Note: This feature is supported for the EJB 2.0 CMP container only, there is no automatic primary key generation support for EJB 1.1 CMP. For 1.1 beans, you must use bean-managed-persistence (BMP.)

Generated key support is provided in two ways:

Note: For instructions on creating a table in Oracle, use the Oracle database documentation.

In the weblogic-cmp-rdbms-jar.xml file, set the key_cache_size element to specify how many primary key values a database SELECT and UPDATE will fetch at one time. The default value of key_cache_size is 1. BEA recommends that you set this element to a value of >1, to minimize database accesses and to improve performance. For more information in this feature, see Specifying Primary Key Named Sequence Table Support.

At this time, WebLogic Server only provides DBMS primary key generation support for Oracle and Microsoft SQL Server. However, you can use named/sequence tables with other unsupported databases. Also, this feature is intended for use with simple (non-compound) primary keys.

Note: The key field must be declared to be of type java.lang.Integer in the abstract `get' and `set' methods of the bean.

Valid Key Field Values

In the abstract `get' and `set' methods of the bean, you can declare the field to be either of the following two types:

Specifying Primary Key Support for Oracle

Generated primary key support for Oracle databases uses Oracle's SEQUENCE feature. This feature works with a Sequence entity in the Oracle database to generate unique primary keys. The Oracle SEQUENCE is called when a new number is needed.

Once the SEQUENCE already exists in the database, you specify automatic key generation in the XML deployment descriptors. In the weblogic-cmp-rdbms-jar.xml file, you specify automatic key generation as follows:

Figure 5-7 Specifying automatic key generation for Oracle

<automatic-key-generation>
	<generator-type>ORACLE</generator-type>
	<generator_name>test_sequence</generator-name>
	<key-cache-size>10</key-cache-size>
</automatic-key-generation>

Specify the name of the ORACLE SEQUENCE to be used, using the generator-name element. If the ORACLE SEQUENCE was created with a SEQUENCE INCREMENT value, then you must specify a key-cache-size. This value must match the Oracle SEQUENCE INCREMENT value. If these two values are different, then you will most likely have duplicate key problems.

Specifying Primary Key Support for Microsoft SQL Server

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 IDENTITY column.

Note: For instructions on creating a table in Microsoft SQL Server, see the Microsoft SQL Server database documentation.

Once the IDENTITY column is created in the database table, you specify automatic key generation in the XML deployment descriptors. In the weblogic-cmp-rdbms-jar.xml file, you specify automatic key generation as follows:

Figure 5-8 Specifying automatic key generation for Microsoft SQL

<automatic-key-generation>
	<generator-type>SQL_SERVER</generator-type>
</automatic-key-generation>

The generator-type element lets you specify the primary key generation method that you want to use.

Specifying Primary Key Named Sequence Table Support

Generated primary key support for unsupported databases uses a Named SEQUENCE TABLE to hold key values. The table must contain a single row with a single column that is an integer, SEQUENCE INT. This column will hold the current sequence value.

Note: For instructions on creating the table, see the documentation for the specific database product.

Once the NAMED_SEQUENCE_TABLE exists in the database, you specify automatic key generation by using the XML deployment descriptors in the weblogic-cmp-rdbms-jar.xml file, as follows:

Figure 5-9 Specifying automatic key generation for named sequence table support

<automatic-key-generation>
	<generator-type>NAMED_SEQUENCE_TABLE</generator-type>
	<generator_name>MY_SEQUENCE_TABLE_NAME</generator-name>
	<key-cache-size>100</key-cache-size>
</automatic-key-generation>

Specify the name of the SEQUENCE TABLE to be used, with the generator-name element. Using the key-cache-size element, specify the optional size of the key cache that tells you how many keys the container will fetch in a single DBMS call.

For improved performance, BEA recommends that you set this value to >1, a number greater than one. This setting reduces the number of calls to the database to fetch the next key value.

Also, it is recommended that you define one NAMED SEQUENCE table per bean type. Beans of different types should not share a common NAMED SEQUENCE table. This reduces contention for the key table.

 


Automatic Table Creation

You can specify that WebLogic Server automatically create tables based on the descriptions in the XML deployment descriptor files and the bean class, if the table does not already exist. Tables are created for all beans and relationship join tables, if the relationships in the JAR files have joins. You explicitly turn on this feature by defining it in the deployment descriptors per each RDBMS deployment, for all beans in the JAR file.

WebLogic Server makes a best attempt to create the new table. However, if based on the descriptions in the deployment files, the field cannot be successfully mapped to an appropriate column type in the database, the TABLE CREATION fails, an error is thrown, and you must create the table yourself.

Automatic table creation is not recommended for use in a production environment. It is better suited for the development phase of design and prototype work. A production environment may require the use of more precise table schema definitions, for example; the declaration of foreign key constraints.

To define automatic table creation:

  1. In the weblogic-cmp-rdbms-jar.xml file, set the create-default-dbms-tables element to True to explicitly turn on automatic table creation for all beans in the JAR file.

  2. Use the following syntax:

    <create-default-dbms-tables>True</create-default-dbms-tables>

Because automatic table creation may not map every Java field type successfully to your target database, the following list is provided to give you an idea of the type of mapping you can expect to see.

Table 5-1 Java Field Types

Java Type

DBMS Column Type

boolean

INTEGER

byte

INTEGER

char

CHAR

double

DOUBLE PRECISION

float

FLOAT

int

INTEGER

long

INTEGER

short

INTEGER

java.lang.string

VARCHAR (150)

java.lang.BigDecimal

DECIMAL (38, 19)

java.lang.Boolean

INTEGER

java.lang.Byte

INTEGER

java.lang.Character

CHAR (1)

java.lang.Double

DOUBLE PRECISION

java.lang.Float

FLOAT

java.lang.Integer

INTEGER

java.lang.Long

INTEGER

java.lang.Short

INTEGER

java.sql.Date

DATE

java.sql.Time

DATE

java.sql.Timestamp

DATETIME

byte[ ]

RAW (1000)

Any serializable Class that is not a valid SQL type:

RAW (1000)

 


Container-Managed Relationships

The entity bean relies on container-managed persistence to generate the methods that perform persistent data access for the entity bean instances. The generated methods transfer data between entity bean instances and the underlying resource manager. Persistence is handled by the container at runtime. The advantage of using container-managed persistence is that the entity bean can be logically independent of the data source in which the entity is stored. The container manages the mapping between the logical and physical relationships at runtime and manages their referential integrity.

Persistent fields and relationships make up the entity bean's abstract persistence schema. The deployment descriptors indicate that the entity bean uses container-managed persistence, and these descriptors are used as input to the container for data access.

Entity beans can have relationships with other beans. You specify relationships in the ejb-jar.xml file and weblogic-cmp-rdbms-jar.xml. You specify container-managed field mappings in the weblogic-cmp-rdbms-jar.xml file.

When a bean with a relationship to another bean is removed, the container automatically removes the relationship.

Relationship Cardinality

WebLogic Server supports three types of relationship mappings that are managed by WebLogic container-managed persistence (CMP):

Relationship Direction

Container-managed relationships can be either bidirectional or unidirectional.

Local Interfaces and Container-Managed Relationships

WebLogic Server provides support for local interfaces for session and entity beans. Local interfaces allow enterprise javabeans to work together within the same EJB container using different semantics and execution contexts. The EJBs are usually co-located within the same EJB container and execute within the same Java Virtual Machine (JVM). This way, they do not use the network to communicate and avoid the overhead of a Java Remote Method Invocation-Internet Inter-ORB Protocol (RMI-IIOP) connection.

EJB relationships with container-managed persistence are now based on the EJB's local interface. Any EJB that participates in a relationship must have a local interface. Local interface objects are lightweight persistent objects. They allow you to do more fine grade coding than do remote objects. Local interfaces also use pass-by-reference. The getter is in the local interface.

In earlier versions of WebLogic Server, you can base relationships on remote interfaces. However, CMP relationships that use remote interfaces should probably not be used in new code.

The EJB container makes the local home interface accessible to local clients through JNDI. To reference a local interface you need to have a local JNDI name. The objects that implement the entity beans' local home interface are called EJBLocalHome objects.

In pre-6.1 versions of WebLogic Server, ejbSelect methods were used to return remote interfaces. Now you can specify a result-type-mapping element in the ejb-jar.xml file that indicates whether the result returned by the query will be mapped to a local or remote object.

Using the Local Client

A local client of a session bean or entity bean can be another EJB, such as a session bean, entity bean, or message-driven bean. A local client can be a servlet as long as it is included as part of the same EAR file and as long as the EAR file is not remote. Clients of a local bean must be part of an EAR or a standalone JAR.

A local client accesses a session or entity bean through the bean's local interface and local home interfaces. The container provides classes that implement the bean's local and local home interfaces. The objects that implement these interfaces are local Java objects. The following diagram shows the container with a local client and local interfaces.

Figure 5-10 Local client and local interfaces

WebLogic Server provides support for both local and uni-directional remote relationships between EJBs. If the EJBs are on the same server and are part of the same JAR file, they can have local relationships. If the EJBs are not on the same server, the relationships must be remote. For a relationship between local beans, multiple column mappings are specified if the key implementing the relation is a compound key. For a remote bean, only a single column-map is specified, since the primary key of the remote bean is opaque. No column-maps are specified if the role just specifies a group-name. No group-name is specified if the relationship is remote.

Changes to the Container for Local Interfaces

Changes made to the structure of the container to accommodate local interfaces include the following additions:

Defining Container-Managed Relationships

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:

Specifying Relationship in ejb-jar.xml

Container-managed relationships are defined in the ejb-relation stanza of ejb-jar.xml. Figure 5-11 shows the ejb-relation stanza for a relationship between two entity EJBs: TeacherEJB and StudentEJB.

The ejb-relation stanza contains a ejb-relationship-role for each side of the relationship. The role stanzas specify each bean's view of the relationship.

Figure 5-11 One-to-Many, Bidirectional CMR in ejb-jar.xml

<ejb-relation> 
      <ejb-relation-name>TeacherEJB-StudentEJB</ejb-relation-name>
            <ejb-relationship-role>
                  <ejb-relationship-role-name>teacher-has-student
                  </ejb-relationship-role-name>
                  <multiplicity>One</multiplicity>
                  <relationship-role-source>
                        <ejb-name>TeacherEJB</ejb-name> 
                  </relationship-role-source>
                  <cmr-field>
                          <cmr-field-name>teacher</cmr-field-name>
                  </cmr-field>
      </ejb-relationship-role> 
      <ejb-relationship-role>
            <ejb-relationship-role-name>student-has-teacher
            </ejb-relationship-role-name>
            <multiplicity>Many</multiplicity>
            <relationship-role-source>
                  <ejb-name>StudentEJB</ejb-name> 
            </relationship-role-source>
            <cmr-field>
                  <cmr-field-name>student</cmr-field-name>
                  <cmr-field-type>java.util.Collection
            <cmr-field>
      </ejb-relationship-role> 

Specifying Relationship Cardinality

The cardinality on each side of a relationship is indicated using the <multiplicity> element in its ejb-relationship-role stanza.

In Figure 5-11 the cardinality of the TeacherEJB-StudentEJB relationship is one-to-many—it is specified by setting multiplicity to one on the TeacherEJB side and Many on the StudentEJB side.

The cardinality of the CMR in Figure 5-12, is one-to-one—the multiplicity is set to one in both role stanza for the relationship

Figure 5-12 One-to-One, Unidirectional CMR in ejb-jar.xml

<ejb-relation> 
      <ejb-relation-name>MentorEJB-StudentEJB</ejb-relation-name>
            <ejb-relationship-role>
                  <ejb-relationship-role-name>mentor-has-student
                  </ejb-relationship-role-name>
                  <multiplicity>One</multiplicity>
                  <relationship-role-source>
                        <ejb-name>MentorEJB</ejb-name> 
                  </relationship-role-source>
                  <cmr-field>
                          <cmr-field-name>mentorID</cmr-field-name>
                  </cmr-field>
      </ejb-relationship-role> 
      <ejb-relationship-role>
            <ejb-relationship-role-name>student-has-mentor
            </ejb-relationship-role-name>
            <multiplicity>One</multiplicity>
            <relationship-role-source>
                  <ejb-name>StudentEJB</ejb-name> 
            </relationship-role-source>
      </ejb-relationship-role> 

If a side of a relationship of a relationship has a <multiplicity> of Many, its <cmr-field> is a collection, and you must specify its <cmr-field-type> as java.util.Collection, as shown in the StudentEJB side of the relationship in Figure 5-11. It is not necessary to specify the cmr-field-type when the cmr-field is a single valued object.

Table 5-2 lists the contents of cmr-field for each bean in a relationship, based on the cardinality of the relationship.

Table 5-2 Cardinality and cmr-field-type

If relationship between EJB1 and EJB2 is...

EJB1's cmr-field
contains ...

EJB2's cmr-field
contains is a ...

one-to-one

single valued object

single valued object

one-to-many

single valued object

Collection

many-to-many

Collection

Collection

Specifying Relationship Directionality

The directionality of a CMR by configured by the inclusion (or exclusion) of a cmr-field in the ejb-relationship-role stanza for each side 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 5-11.

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 5-12 specifies a unidirectional relationship from MentorEJB to StudentEJB— there is no cmr-field element in the ejb-relationship-role stanza for StudentEJB.

Specifying Relationships in weblogic-cmp-jar.xml

Each CMR defined in ejb-jar.xml must also be defined in a weblogic-rdbms-relation stanza in weblogic-cmp-jar.xml. weblogic-rdbms-relation identifies the relationship, and 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 ejb-jar.xml.

One-to-One and One-to-Many Relationships

For one-to-one and one-to-many relationships, column-map is defined for only one side of the relationship.

For one-to-one relationships, the mapping is from a foreign key in one bean to the primary key of the other.

Figure 5-13 is the weblogic-rdbms-relation stanza for a the one-to-one relationship between MentorEJB and StudentEJB, whose <ejb-relation> is shown in Figure 5-12.

Figure 5-13 One-to-One CMR weblogic-cmp-jar.xml

<weblogic-rdbms-relation>
      <relation-name>MentorEJB-StudentEJB</relation-name>
      <weblogic-relationship-role>
              <relationship-role-name>
              mentor-has-student
              <column-map>
                    <foreign-key-column>student</foreign-key-column>
                    <key-column>StudentID/key-column>
              </column-map>
        </weblogic-relationship-role>

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.

Figure 5-14 is the weblogic-rdbms-relation stanza for a the one-to-many relationship between TeacherEJB and StudentEJB, whose <ejb-relation> is shown in Figure 5-11.

Figure 5-14 weblogic-rdbms-relation for a One-to-Many CMR

<weblogic-rdbms-relation>
      <relation-name>TeacherEJB-StudentEJB</relation-name>
      <weblogic-relationship-role>
              <relationship-role-name>
              teacher-has-student
              </relationship-role-name>
              <column-map>
                      <foreign-key-column>student</foreign-key-column>
                      <key-column>StudentID/key-column>
                </column-map>
      </weblogic-relationship-role>

Many-to-Many Relationships

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.

Figure 5-15 shows the weblogic-rdbms-relation stanza for the friends relationship between two employees.

The FRIENDS join table has two columns, first-friend-id and 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.

Figure 5-15 weblogic-rdbms-relation for a Many-to-Many CMR

<weblogic-rdbms-relation>
    <relation-name>friends</relation-name>
    <table-name>FRIENDS</table-name>
    <weblogic-relationship-role>
        <relationship-role-name>first-friend
        </relationship-role-name>
            <column-map>
                <foreign-key-column>first-friend-id</foreign-key-column>
                <key-column>id</key-column>
          </column-map
    <weblogic-relationship-role>
        <weblogic-relationship-role>
            <relationship-role-name>second-friend</relationship-role-
            name>
            <column-map>
                <foreign-key-column>second-friend-id</foreign-key-column>
                <key-column>id</key-column>
            </column-map>
      </weblogic-relationship-role>
</weblogic-rdbms-relation>

Container-Managed Relationships and Caching

In versions of WebLogic Server up to and including WebLogic Server 6.1, loading a bean that participates in a container-managed relationship into the cache does not cause related instances to be loaded into cache.

Consider the following EJB code for accountBean and addressBean, which have a 1-to-1 relationship:

Account acct = acctHome.findByPrimaryKey("103243");
Address addr = acct.getAddress();

Execution of this code results in two database queries. The first line results in an SQL query to load accountBean. The second line results in another query to load addressBean.

 


Groups

In container-managed persistence, you use groups to specify certain persistent attributes of an entity bean. A field-group represents a subset of the cmp and CMR-fields of a bean. 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 persistent state of the bean.

A field can belong to multiple groups. In this case, the getXXX() method for the field will fault in the first group that contains the field.

Specifying Field Groups

Field groups are specified in the weblogic-rdbms-cmp-jar.xml file as follows:

<weblogic-rdbms-bean>
	<ejb-name>XXXBean</ejb-name>
	<field-group>
		<group-name>medical-data</group-name>
		<cmp-field>insurance</cmp-field>
		<cmr-field>doctors</cmr-fields>
	</field-group>
</weblogic-rdbms-bean>

You use field groups when you want to access a subset of fields.

 


Java Data Types for CMP Fields

The following table provides a list of the Java data types for CMP fields used in WebLogic Server and shows how they map to the Oracle extensions for the standard SQL data types.

Table 5-3 Java data types for CMP fields

Java Types for CMP Fields

Oracle Data Types

boolean

SMALLINT

byte

SMALLINT

char

SMALLINT

double

NUMBER

float

NUMBER

int

INTEGER

long

NUMBER

short

SMALLINT

java.lang.String

VARCHAR/VARCHAR2

java.lang.Boolean

SMALLINT

java.lang.Byte

SMALLINT

java.lang.Character

SMALLINT

java.lang.Double

NUMBER

java.lang.Float

NUMBER

java.lang.Integer

INTEGER

java.lang.Long

NUMBER

java.lang.Short

SMALLINT

java.sql.Date

DATE

java.sql.Time

DATE

java.sql.Timestamp

DATE

java.math.BigDecimal

NUMBER

byte[]

RAW, LONG RAW

serializable

RAW, LONG RAW

Do not use the SQL CHAR data type for database columns that are mapped to CMP fields. This is especially important for fields that are part of the primary key, because padding blanks that are returned by the JDBC driver can cause equality comparisons to fail when they should not. Use the SQL VARCHAR data type instead of SQL CHAR.

A CMP field of type byte[] cannot be used as a primary key unless it is wrapped in a user-defined primary key class that provides meaningful equals() and hashCode() methods. This is because the byte[] class does not provide useful equals and hashCode.

 

back to top previous page next page