Skip Headers
Oracle® Containers for J2EE Services Guide
10g Release 3 (10.1.3)
B14427-01
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

4 Data Sources

This chapter discusses Data Sources in Oracle Containers for J2EE (OC4J). It contains the following sections:

Tasks

The following OC4J Data Source tasks are described in this chapter:

What's New in 10.1.3

The following OC4J Data Source features and behaviors are new for this release:

Deprecated

The following item(s) are deprecated in this release:

Additional Documentation

The following documents give additional data source information:

4.1 Data Source Types

A data source is a Java object that implements the javax.sql.DataSource interface. Data sources offer a portable, vendor-independent method for creating connections to databases. A data source object's properties are set so that it represents a particular database. An application can use a different database by changing the data source's properties; no change in the application code is required.

OC4J provides two types of data sources: managed and native.

4.1.1 Managed Data Sources

Managed data sources are managed by OC4J. This means that OC4J provides critical system infrastructure such as global transaction management, connection pooling, and error handling. A managed data source is an OC4J-provided implementation of the javax.sql.DataSource interface that acts as a wrapper to a JDBC driver or data source. J2EE components access managed data sources via JNDI with no knowledge that the data source implementation is a wrapper.

Managed data sources differ from native data sources as follows:

  • The connections retrieved from a managed data source can participate in global transactions.

  • A managed data source uses OC4J's connection pool and statement cache.

  • A connection returned from a managed data source is wrapped with an OC4J Connection proxy.

4.1.2 Native Data Sources

Native data sources implement the javax.sql.DataSource interface and are provided by JDBC driver vendors (such as Oracle and DataDirect.) Native data sources differ from managed data sources as follows:

  • The connections retrieved from a native data source cannot participate in global transactions.

  • A native data source does not use OC4J's connection pool or statement cache.

  • A connection returned from a native data source is not wrapped with an OC4J Connection proxy.

For information on configuring native data sources, see Defining a Native Data Source.

4.2 Defining Data Sources

The Application Server Control Console is your primary tool for managing data sources including operations to create data sources and connection pools, remove data sources and connection pools, and modify existing data sources and connection pools.

The online help in the Application Server Control Console provides useful information on data source settings.

When the data sources are modified in the Application Server Control Console, the data source settings are immediately persisted to the data-sources.xml file for that application.

The default application's data sources configuration file is located in $J2EE_HOME/config/data-sources.xml.

Each <data-source> tag in this file represents one data source that is bound into JNDI and therefore accessible from client components (servlets, EJBs, etc.)

This section shows examples of data source definitions in the data-sources.xml configuration file.

For more information on defining data sources, see "Configuring Data Source Objects".

For examples of the data-sources.xml file, see the Configuration Examples section.

Configuration Notes

When a data source is added, edited, or deleted directly in the data-sources.xml file, you must restart OC4J to implement the changes.

When a data source is added, edited, or deleted in the Application Server Control Console, it is not necessary to restart OC4J to implement the changes.

Each time you save your data source settings in the Application Server Control Console, a new data-sources.xml file is generated and comments are lost.

The jndi-name of a data source must be unique for an application. You cannot have duplicate jndi names in the same data-sources.xml file. For 10.1.3, OC4J throws an exception if jndi location is repeated within a data-sources.xml file. You may specify a jndi-name in the data-sources.xml file for an application that has already been specified in the global data-sources.xml file. In this case, jndi locations specified in the application data-sources.xml serve as overrides for those locations in the application context.

Data sources are defined using the <data-source> tag. The class attribute can be set to any full-path class name of the object implementing the javax.sql.DataSource interface.

Certain well-defined properties are specified in this tag as well such as user, password, url, and so on.Properties that OC4J does not know about can be defined using a <property> tag.

OC4J-specific implementations DO NOT have any extra properties that can be set. That is, all of their properties are set be means of the values specified in the <data-source> tag.

Oracle-specific implementations such as oracle.jdbc.pool.OracleDataSource DO have properties that can be set by means of the <property> sub tag of the <data-source> tag.

For information about Oracle JDBC drivers, see the Oracle Database JDBC Developer's Guide and Reference.

Non-Oracle vendor-specific implementations, such as DB2, Sybase, SQLServer, etc. most likely also have properties outside of the ones defined in the <data-source> tag that can be defined using the <property> tag. It is up to the user to determine the properties of non-Oracle data source implementations.

4.2.1 Defining a Connection Pool

A managed data source uses a connection pool to efficiently manage connections. If you will create managed data sources, you must define at least one connection pool and its connection factory.

OC4J provides the connection pool feature to increase efficiency for managed data sources by maintaining a cache of physical connections that can be reused. When a client closes a connection, the connection gets placed back into the pool so that another client can use it. A connection pool improves performance and scalability by allowing multiple clients to share a small number of physical connections.


Note:

The terms "connection pool" and "connection cache" are synonymous.

For more information on the nature and purpose of connection pools, see Using Connection Pools for Managed Data Sources.

Path to Connection Factory and Connection Pool Settings in the Application Server Control Console

OC4J:Home > Administration tab > Task Name: Services > JDBC Resources: Go To Task > Drill down to desired settings.

Here is an example of defining a connection pool in the data-sources.xml file instead of the Application Server Control Console.

<connection-pool name="myConnectionPool">
    <connection-factory 
        factory-class="oracle.jdbc.pool.OracleDataSource"
        user="scott"
        password="tiger"
        url="jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com"/>
         <property name="foo" value="bar"/>
    </connection-factory>
</connection-pool>

The <connection-pool> element contains a name attribute that uniquely identifies the connection pool. Other attributes define parameters for the connection pool such as the maximum number of connections that the connection pool will hold. A connection pool uses a connection factory (defined by the <connection-factory> element) to get physical connections from the database.

The <connection-factory> element contains the URL that the JDBC driver uses to connect to the database plus an optional default user and password that can be used to get connections from the database. The factory-class attribute defines the implementation class provided by the JDBC driver that is used to get the connections. The implementation class must be an implementation of one of the following:

  • java.sql.Driver

  • javax.sql.DataSource

  • javax.sql.XADataSource

  • javax.sql.ConnectionPoolDataSource.

For details on connection pool and connection factory settings, see Table 4-3, "Connection Pool Attributes".

4.2.2 Defining a Managed Data Source

After you have defined at least one connection pool you can define a managed data source.

Path to Managed Data Source Settings

OC4J:Home > Administration tab > Task Name: Services > JDBC Resources: Go To Task > Data Sources > Create > Select Application > Select Data Source Type > Managed

Here's an example of a managed data source definition in the data-sources.xml file using the connection pool defined above:

<managed-data-source
    jndi-name="jdbc/ManagedDS"
    name="Managed DataSource Name"
    connection-pool-name="myConnectionPool"/>

The name attribute uniquely identifies the managed data source. The jndi-name attribute defines the location with which this data source will be placed into JNDI. The connection-pool-name attribute identifies the connection pool with which this managed data source will interact to get connections. This connection pool name corresponds to the value specified for the name attribute in the <connection-pool> element in the example in the example in the previous section "Defining a Connection Pool".

4.2.3 Defining a Native Data Source

A native data source has no dependencies on a connection pool. As such, a native data source definition includes data required to communicate with the underlying database.

Path to Native Data Source Settings

OC4J:Home > Administration tab > Task Name: Services > JDBC Resources: Go To Task > Data Sources > Create > Select Application > Select Data Source Type > Native

Here's an example of native data source definition in the data-sources.xml file:

<native-data-source
    name="nativeDataSource"
    jndi-name="jdbc/nativeDS"
    data-source-class="com.acme.DataSourceImpl"
    user="frank"
    password="frankpw"
    url="jdbc:acme:@localhost:5500:acme">
</native-data-source>

Additional data source configuration examples are shown in the article Data Source Configuration in Oracle Application Server 10g available at http://www.oracle.com/technology/tech/java/newsletter/articles/oc4j_datasource_config.html

The name attribute uniquely identifies the native data source. The jndi-name attribute defines the location with which this data source will be placed into JNDI. The data-source-class attribute defines the implementation class of the native data source and must be an implementation of javax.sql.DataSource. The user and password attributes define the default user and password. The url attribute defines the url that the data source will use to communicate with the database.

4.2.4 Defining Fatal Error Codes

For each data source defined in data-sources.xml, you can define fatal error codes that indicate that the back-end database with which the data source communicates is no longer accessible. When OC4J detects one of these error codes (stated when a SQLException is thrown by the JDBC driver), OC4J will clean its connection pool. That is, it closes all connections in the connection pool. For Oracle, the predefined fatal error codes are: 3113, 3114, 1033, 1034, 1089, and 1090.

Use the following procedure to define fatal error codes for non-Oracle databases or to add additional fatal error codes for Oracle databases.

Use the <fatal-error-codes> element, which is a subtag of the <connection-factory> element. The <fatal-error-codes> element uses the child element <error-code> to define one fatal error code. You can define 0 - n <error-code> elements for each <fatal-error-codes> element. For example, for fatal error codes 10, 20, and 30, the data source definition would look like this:

<connection-pool name="myConnectionPool">
 <connection-factory factory-class="oracle.jdbc.pool.OracleDataSource"
   user="scott"
   password="tiger"
   url="jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com"/>
 
  <fatal-error-codes>
   <error-code code='10'/>
   <error-code code='20'/>
   <error-code code='30'/>
  </fatal-error-codes>
 </connection-factory>
</connection-pool>

4.2.5 Using Password Indirection

The data-sources.xml file requires passwords for authentication. Embedding these passwords without some kind of obfuscation poses a security risk. To avoid this problem, OC4J supports password indirection.

An indirect password is made up of a special indirection symbol (->) and a user name (or user name and realm). When OC4J encounters an indirect password, it retrieves the password associated with the specified user from the security store provided by a user manager.

For more information on creating users and passwords, and working with a user manager, see the section on password management in the Oracle Containers for J2EE Security Guide.

For example, if the native data source entry looks like:

<native-data-source
    name="nativeDataSource"
    jndi-name="jdbc/nativeDS"
    data-source-class="com.acme.DataSourceImpl"
    user="frank"
    password="frankpw"
    url="jdbc:acme:@localhost:5500:acme">
    </native-data-source>
 

You can replace the password, "frankpw", with the indirection symbol (->) and a user name (frank) as follows: password="->frank". This assumes that a user named frank with the password frankpw has been created in a user manager.

You can configure password indirection in the Application Server Control Console.

To configure an indirect password for a data source directly in the data-sources.xml file and change the value of the password attribute so that its value is "->", followed either by the username or by the realm and user separated by a slash ("/"). Here is an example:

<native-data-source
    name="nativeDataSource"
    jndi-name="jdbc/nativeDS"
    data-source-class="com.acme.DataSourceImpl"
    user="frank"
    password="->frank"
    url="jdbc:acme:@localhost:5500:acme">
</native-data-source>

Note that there are password attributes for <native-data-source>, <managed-data-source>, and <connection-factory> elements.

4.3 Connections

OC4J data sources return two types of connections:

4.3.1 Establishing a Connection

A data source produces connections by communicating with a database. Typically a data source uses a URL to identify the machine, port, and database name, etc. that it uses to communicate with that database.

For a managed data source, the URL is defined in that managed data source's connection pool's connection factory. The connection factory's url attribute defines the URL that is used to communicate with the database. The JDBC driver defines the format of the URL. Several examples of the URL are provided throughout this document.

For a native data source, the URL is defined by the url attribute of the <native-data-source> element.

4.3.2 Using Connection Pools for Managed Data Sources

Basic implementations of data sources have a one-to-one correspondence between a client's connection object and a physical connection. When the client closes the connection, the physical connection is typically dropped. This incurs a lot of overhead each time a client retrieves a connection from the data source.

OC4J's managed data sources make frequent use of connection pools.

A connection pool can be used by more than one managed data source; that is, multiple managed data sources can share the same connection pool.

When a data source is defined to use the Oracle 10g JDBC driver, OC4J uses the sophisticated connection pool that is provided by the Implicit Connection Cache (ICC) that comes with that driver. OC4J data sources automatically use the ICC. All of the connection pool attributes described in Table 4-3, "Connection Pool Attributes" apply to the ICC, unless otherwise specified. Some of the attributes apply only to Implicit-Connection-Cache-enabled data sources (OracleDataSource and OracleXADataSource). There is no additional configuration necessary to use the ICC.

For information on connection pool configuration settings, see Table 4-3, "Connection Pool Attributes".

Connection pools are also provided for non-Oracle JDBC drivers and previous versions of Oracle JDBC drivers. An example of configuring a connection pool are described in the Configuration Examples section.

4.3.3 Using Connection Proxies with Managed Data Sources

When using managed data sources, OC4J wraps each connection retrieved from the connection pool with a proxy object. This proxy enables OC4J to provide transaction enlistment, exception handling, and logging.

Vendor-Specific Extensions

Clients can also use extensions to the java.sql interfaces that are provided by the vendor implementations of these interfaces. For example, the Oracle extension of the java.sql.Connection interface is the oracle.jdbc.OracleConnection. This interface provides Oracle-specific APIs that are not part of the java.sql.Connection interface. OC4J provides a configuration element that allows you to limit the interfaces that the proxy should implement so that the client has access to only those APIs. This configuration element can be used to specify additional interfaces for any of the java.sql.* interfaces. By default the proxies implement any public interface that is implemented by the underlying object.

For information on setting proxies, see Table 4-3, "Connection Pool Attributes".

Here is an example of defining a connection proxy and a statement proxy for a connection pool in a data-sources.xml file instead of the Application Server Control Console.

<connection-pool name="myConnectionPool">
    <connection-factory 
        factory-class="com.acme.AcmeDataSource"
        user="scott"
        password="tiger"
        url="jdbc:acme:@localhost:1234:acme"/>
        <property name="foo" value="bar"/>
        <proxy-interface sql-object="Connection"
        interface="com.acme.AcmeConnection"/>
        <proxy-interface sql-object="CallableStatement"
        interface="com.acme.AcmeCallableStatement"/>
    </connection-factory>
</connection-pool>

In this example, proxies generated for Connection objects would only expose the com.acme.AcmeConnection interface, regardless of what other interfaces are implemented by the underlying connection object. Likewise, proxies generated for Statement objects would only expose the com.acme.AcmeStatement interface. This gives the data source deployer a way to limit the interfaces exposed by the proxy objects.

4.3.4 Getting a Connection From a DataSource

This section provides sample code for getting a connection from a data source and executing a statement.


Notes:

Take care to always close a connection that is retrieved from a data source even when exceptions are thrown.

The string used to perform the lookup must match the value of a JNDI Location jndi-name setting in a managed data source or a native data source.


   Connection connection = null;
   try {
      InitialContext context = new InitialContext();
      DataSource ds = (DataSource) context.lookup( "jdbc/ManagedDS" );
      connection = ds.getConnection();
      Statement statement = connection.createStatement();
      statement.execute( "select * from dual" );
      statement.close();
   }
   catch( Exception exception ) {
      // process exception
   }
   finally {
      if ( connection != null )
      {
         try {
            connection.close();
         }
         catch( SQLException sqlException ){}
      }
   }


Notes:

When using getConnection(), if no user/password is passed in, then the user and password specified in the definition of the connection factory is automatically used and the connection is successfully created. If different user/passwords are specified in connection factory, one pair in attributes and a different pair in properties, then getConnection(), uses the user/password specified in the properties.

Specifying the connection factory user/password is described in Table 4-4, "Connection Factory Attributes".

Connection factory properties is discussed in Connection Factory Properties.


4.3.4.1 Retry

Under certain circumstances a data source may not be able to return a connection. The most common cause for this is when all of the connections in the connection pool are in use. You may want the data source to wait for a period of time and then check the connection pool to see if it has any available connections before returning.

There are two connection pool configuration settings that you can use to control the amount of time to wait if a connection is not available in the pool and the number of times to retry asking the connection pool for a connection.

The max-connect-attempts setting defines the number of times that a managed data source will retry getting a connection from the connection pool (when all of the connection pool's connections are in use.) The connection-retry-interval setting specifies the interval to wait (in seconds) before attempting to get a connection from the connection pool after the last failed attempt. For more on these settings, see Connection Pool Attributes.

Here is an example of configuring the retry in the data-sources.xml instead of the Application Server Control Console. The example sets the max-connect-attempts to 5 seconds and the connection-retry-interval to 3 seconds.

<connection-pool name="myConnectionPool"
max-connect-attempts="5"
connection-retry-interval="3">
  <connection-factory 
    factory-class="oracle.jdbc.pool.OracleDataSource"
    user="scott"
    password="tiger"
      url="jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com"/>
  </connection-factory>
</connection-pool>

4.4 Statements

Managed data sources provide caching and proxies to make working with statements more efficient.

4.4.1 Statement Caching with Managed Data Sources

Statement caching improves performance by caching executable statements that are used repeatedly and makes it unnecessary for programmers to explicitly reuse prepared statements. Statement caching eliminates overhead due to repeated cursor creation, repeated statement parsing and creation and reduces overhead of communication between the application server and the database server. The following is true about statement caching:

  • Statement caching and reuse is transparent to an application.

  • Each statement cache is associated with a physical connection. That is, each physical connection will have its own statement cache.

  • The statement match criteria are the following:

    • The SQL string in the statement must be identical (case-sensitive) to one in the cache.

    • The statement type must be the same (prepared or callable).

    • The scrollable type of result sets produced by the statement must be the same (forward-only or scrollable).

    • Maximum Number of Statements Cached

4.4.1.1 Setting the JDBC Statement Cache Size in Data Sources

To lower the overhead of repeated cursor creation and repeated statement parsing and creation, you can use statement caching with database statements. To enable JDBC statement caching, which caches executable statements that are used repeatedly, configure a datasource to use statement caching. A JDBC statement cache is associated with a particular physical connection maintained by a datasource. A statement cache is not per data source so it is not shared across all physical connections. The JDBC statement cache is maintained in the middle-tier (not in the database server).

You can dynamically enable and disable statement caching programmatically using the setStmtCacheSize() method on the connection object.

To configure JDBC statement caching for a data source, use the num-cached-statements attribute to set the size of the cache. This attribute sets the maximum number of statements to be placed in the cache. If you do not specify the num-cached-statements attribute or set it to 0, the statement cache is disabled.

The following XML sets the statement cache size to 200 statements:

  <data-source>
   ...
  num-cached-statements="200"
  </data-source>

To set the num-cached-statements attribute, first determine how many distinct statements the application issues to the database. Then, set the size of the cache to this number. If you do not know the number of statements that your application issues to the database, you can use the JDBC performance metrics to assist you with determining the statement cache size. To use the statement metrics you need to set the Java property oracle.jdbc.DMSStatementMetrics to true for the OC4J.


Note:

In 10.1.3, to configure JDBC statement caching for a data source, use the num-cached-statements attribute to set the size of the cache. The stmt-cache-size attribute is deprecated.

Statement Cache Size Resource Issues

Even though the num-cached-statements is specified for a data source, statements are cached per connection, not per data source or connection pool. In other words, each managed connection acquired from a given data source will maintain its own statement cache if num-cached-statements is greater than 0 for that data source.

You should be aware that statements held in a connection's statement cache may hold on to database resources. It is possible that the number of opened connections combined with the number of cached statements per connection could exceed the limit of open cursors allowed for the database. You may be able to avoid this problem by reducing the num-cached-statements value or by increasing the limit of open cursors allowed for the database.

4.4.2 Statement Proxies with Managed Data Sources

All implementations of the java.sql.* interfaces (managed data sources) are wrapped by OC4J with a proxy object. This includes the statement objects as well (java.sql.Statement, java.sql.PreparedStatement, and java.sql.CallableStatement).

For information on setting proxies, see the Connection Factory Proxy Interfaces tab description in Table 4-3, "Connection Pool Attributes".

Under certain conditions, a connection proxy may rebind to a new physical connection. This can happen, for example, when a connection proxy is used across a transaction. When this occurs, any statement objects obtained through the connection proxy are no longer valid since they were created using the old physical connection. For this reason, a proxy fronts statement objects acquired from the physical connection as well. These statement proxies are associated with the connection proxy from which they were obtained so that they can monitor the association with the underlying physical connection. If the statement proxy determines that the physical connection associated with its connection proxy has changed, then it will acquire a new physical statement from the connection proxy.

Vendor-specific extensions to the java.sql.Statement, java.sql.PreparedStatement, and java.sql.CallableStatement interfaces can be made available to clients in the same manner as connections.

4.5 Transactions

J2EE supports two kinds of transactions:

Transaction support, including local transactions and global transactions, is discussed in the Chapter 4, "Data Sources",

4.5.1 Local Transactions

When a managed data source is configured for local transactions it returns connections that can participate in local transactions but cannot participate in global transactions. This means that the connections will not be enlisted in global transactions. The data source will set the auto commit to true for retrieved connections. However, it is up to the client to determine how the connections will be used in local transactions. That is, the client can change the auto-commit mode by using setAutoCommit() on a connection.

To set a managed data source for local transactions, see the Transaction Level setting in Table 4-1, "Managed Data Source Settings".

To configure a data source for local transactions in the data-sources.xml file instead of the Application Server Control Console, set the tx-level attribute to "local" (The default value is "global".) Here's an example:

<managed-data-source
jndi-name="jdbc/ManagedDS"
name="Managed DataSource Name"
connection-pool-name="myConnectionPool"
tx-level="local"/>
 

Native data sources can only participate in local transactions so there is no setting for a native data source for transaction support.

It is possible that a connection marked as local will be used inside a global transaction. Although this case is not specifically addressed in the JDBC specification, the specification implies that if a connection is not participating in a distributed transaction then the connection behaves like a local connection. If a connection is not enlisted in a global transaction then it is not participating in the transaction. Therefore a connection produced by a data source that is configured with local transaction will be treated as if it is in a local transaction even if work is performed on it inside a global transaction. That is, if auto commit is set to false, then the work performed on that connection cannot be committed or rolled back until commit or rollback is called on the connection even if the commit or rollback is executed on the distributed transaction. In this case, the connection only appears syntactically with the transaction boundaries, but does not actually participate in that transaction semantically, that is, it is not enlisted.

For example:

  • Get a connection, lc, from a data source configured for local transaction.

  • Begin a global transaction.

  • Get a connection, gc, from a data source that can be used in global transactions.

  • Perform work on both connections.

    The work done on lc may be committed when the work is performed (if auto commit is set to true) or commit/rollback may be called on lc (if auto commit is set to false.)

  • Commit or rollback the global transaction.

    The work done on gc is now committed or rolled back. No work will be committed on lc.

  • The work done on lc may be committed or rolled back by calling commit or rollback on the connection (assuming that auto commit is set to false.)

Here is a code example of the above steps:

Connection lc = localTxDataSource.getConnection();
userTransaction.begin();
Connection gc = globalTxDataSource.getConnection();
lc.doWork();
gc.doWork();
userTransaction.commit();
// At this point work done on gc is now committed.  
//The work done on lc is NOT yet committed.
lc.commit();
// At this point work done on lc is now committed.  

4.5.1.1 Local Transaction Management

Typically a local transaction begins when a client sets autoCommit to false on a connection and the local transaction ends when the client calls commit() or rollback() on that connection. If no transactional work has been performed on the connection when autoCommit is false then explicitly calling commit() or rollback() on the connection may be deemed as unnecessary (the driver may be smart enough to know that no transactional work was done so committing or rolling back is not necessary.)

OC4J determines that there is an active local transaction on a connection when autoCommit is false and any method, other than commit(), rollback(), setAutoCommit(true), or close() has been called on the connection (note that OC4J cannot determine if the work done on the connection is actually transactional or not.) Calling commit(), rollback(), or changing the value of autoCommit ends the current local transaction. If autoCommit is false and a method (other than commit(), rollback(), setAutoCommit(true), or close) is subsequently called on the connection then OC4J considers this the beginning of a new local transaction.

What happens when the client does not explicitly end the local transaction (by calling commit(), rollback(), or setAutoCommit(true)) for the connection? There are two cases to consider:

  • In the first case the client there is an active local transaction and the user closes the connection.

  • In the second case there is an active local transaction and the connection is used in a global transaction.

OC4J can handle these cases in two ways:

  • OC4J can manage local transactions and intercede when the connection is closed or when the connection is used in the global transaction. More specifically, OC4J can implicitly end the local transaction by calling commit() or rollback(). OC4J can also throw an exception when the connection is closed or when the connection is used in a global transaction.

  • OC4J cannot manage local transactions and will not intercede in these cases. More specifically, when a connection is closed or when a connection is used in a global transaction, then the resource must determine how to end the local transaction (or not end it.) Note that when OC4J is configured to not manage local transactions it is possible that when a connection is placed back into the connection pool it will have an uncommitted local transaction active.

4.5.2 Global Transactions (XA)

When a managed data source is configured for global transactions, it returns connections that can participate in global transactions. A global transaction (also called a distributed transaction) enlists more than one resource in the transaction.

For information on how the transaction manager deals with global transactions when there are outstanding JCA local transactions, see "Local Transaction Management".

For more on transactions, see Chapter 5, "OC4J Transaction Support".

To set a managed data source for global transactions, see the Transaction Level setting in Table 4-1, "Managed Data Source Settings".

To configure a data source for global transactions in the data-sources.xml file instead of the Application Server Control Console, either do not include the tx-level attribute (The default is "global".) or set the tx-level attribute to global. Here's an example:

<managed-data-source
    jndi-name="jdbc/ManagedDS"
    name="Managed DataSource Name"
    connection-pool-name="myConnectionPool"
    tx-level="global"/>
 

4.5.2.1 XA Recovery

When a global transaction fails, the transaction manager must perform XA recovery. To do this, it must have some information defined for it for each resource to be recovered. For data sources this means defining a recovery username and password for each connection factory that uses a javax.sql.XADataSource as its factory-class.

See the User and Password settings in Table 4-3, "Connection Pool Attributes"

Here's an example of configuring XA recovery in the data-sources.xml file instead of the Application Server Control Console. Note the xa-recovery-config node.

<connection-pool name="myConnectionPool">
    <connection-factory 
        factory-class="oracle.jdbc.xa.client.OracleXADataSource"
        user="scott"
        password="tiger"
        url="jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com"/>
            <xa-recovery-config>
                <password-credential>
                    <username>system</username>
                    <password>manager</password>
                </password-credential>
            </xa-recovery-config>
        </connection-factory>
</connection-pool>


Notes:

  • If the factory-class is an instance of java.sql.Driver, javax.sql.DataSource, or javax.sql.ConnectionPoolDataSource then the XA recovery configuration is not necessary. for more information, see "Emulating XA".

  • OracleXADataSource is also an instance of javax.sql.XADataSource.


4.5.2.2 Emulating XA

An emulated XAResource is an implementation of javax.sql.XAResource that emulates the semantics of the XA protocol. This means that during a global transaction, those connections that are associated with an emulated XAResource follow the semantics of XA by using local transactions rather than transaction branches controlled explicitly as a subset of the global unit of work.

Emulating an XAResource is needed to support JDBC drivers that do not supply implementations of javax.sql.XADataSource. Also, an emulated XAResource will perform faster than a true XAResource since the performance of an emulated XAResource will not be affected by the overhead associated with true two-phase commit.

Note that using emulated XAResources can lead to inconsistent or non-recoverable outcomes when more than one XAResource is enlisted and at least one of them is emulated. The reason for this is that during the prepare phase an emulated XAResource does not perform a true prepare because it is using a local transaction. One way that this can be a problem is that when commit is called on the emulated XAResource its local transaction may have timed out which causes the local transaction's commit to fail which in turn causes the entire transaction to be in an inconsistent state.

OC4J automatically determines when to emulate XA behavior. It does this by introspecting the connection factory's factory-class object (the factory-class attribute specifies the object that is used by the connection factory to create connections for the connection pool.) If this object is an instance of javax.sql.XADataSource then OC4J does NOT emulate XA. If this object is an instance of java.sql.Driver, javax.sql.DataSource, or javax.sql.ConnectionPoolDataSource then OC4J emulates XA behavior for this data source.

4.6 Configuring Data Source Objects

This section lists and describes the configuration settings for the various data-source-related objects, whether you make the settings in the Application Server Control Console or directly in the data-sources.xml file.

The settings are discussed in the following tables:

For more information on configuring data source objects, see "Defining Data Sources".

4.6.1 Managed Data Sources

You must define at least one connection pool before you can define a managed data source.

Path to Managed Data Source Settings

OC4J:Home > Administration tab > Task Name: Services > JDBC Resources: Go To Task > Data Sources > Create > Select Application > Select Data Source Type > Managed

Here's an example of a managed data source definition in data-sources.xml:

<managed-data-source
  jndi-name="jdbc/ManagedDS"
  name="Managed DataSource Name"
  connection-pool-name="myConnectionPool"/>

Table 4-1 Managed Data Source Settings

Application Server Control Console Property <managed-data- source> Attribute Description

Name

name

Required. The name of the data source. This must be a unique value.

This name is used as the "name" key property of the JDBCDataSource managed object (j2eeType=JDBCDataSource,name=data source name).

JNDI Location

jndi-name

Required. The JNDI logical name for the data source object. OC4J binds an instance of the data source into the application JNDI namespace with this value.

Connection Pool

connection-pool-name

Required. The name of the connection pool that this managed data source uses to get connections.

Schema

schema

The path to the database schema for this data source when using the Orion CMP implementation for EJBs. This is provided for backward compatibility.

Transaction Level

tx-level

The transaction level supported by this managed data source.

A value of local indicates that this data source and the connections it produces may participate in local transactions only.

A value of global indicates that this data source and the connections it produces may participate in local and global transactions.

Optional. Default = global.

Local Transaction Management

manage-local-transactions

Specifies whether or not OC4J should manage local transactions.

  • If true, then the following happens when autoCommit is false for a connection:

    When close() is called on a connection, OC4J calls commit() on the connection before calling close().

    If the connection is used in a global transaction, then OC4J calls rollback() on the connection and throws an exception.

  • If false, then the following happens when autoCommit is false for a connection:

    When close() is called on a connection, OC4J will not call commit() on the connection before calling close(). The JDBC driver determines how to handle the local transaction.

    If the connection is used in a global transaction, then OC4J will not call rollback() on the connection nor will it throw an exception. The JDBC driver determines how to handle the local transaction.

Optional. Default = true.

SQL Object Management

manage-sql-objects

Determines how OC4J manages the java.sql.* objects. Managing one of these objects means that OC4J will wrap the object in a proxy and will intercept the methods that are invoked on the objects.

A value of all means that OC4J will manage all java.sql.* objects.

A value of basic means that OC4J will manage only java.sql.Connection, java.sql.Statement, java.sql.PreparedStatement, and java.sql.CallableStatement.

Optional. Default = basic.

Login Timeout

login-timeout

The maximum time, in seconds, that this data source will wait while attempting to connect to a database. A value of 0 (zero) specifies that the timeout is the default system timeout if there is one; otherwise, it specifies that there is no timeout.

Optional. Default = 0

User

user

The default user to use to connect to the database.

Optional. No default.

Password

password

The default password to use to connect to the database.

Optional. No default.


4.6.2 Native Data Source

Path to Native Data Source Settings

OC4J:Home > Administration tab > Task Name: Services > JDBC Resources: Go To Task > Data Sources > Create > Select Application > Select Data Source Type > Native

  • A native data source has no dependencies on a connection pool. As such, a native data source definition includes data required to communicate with the underlying database.

  • Each <native-data-source> tag defines one native data source.

  • Native data source settings are described in Table 4-2, "Native Data Source Settings".

  • Each "native-data-source" tag may have 0 or more "property" tags. Each "property" tag defines a property on the native data source instance. Reflection will be used on the native data source object to set the property's value. The property name must match (case sensitive) the name of the setter method used to set the property. For example, if there exists on the connection factory object a property named "MyProp" then a method named "setMyProp" will be called to set the property. Therefore the "property" tag's name must be "MyProp" in order to set the property correctly.

<native-data-source 
   name='My Native DataSource'
   jndi-name='jdbc/nativeDs'
   data-source-class='com.acme.DataSourceImpl'
   user='frank'
   password='frankpw' 
   url='jdbc:acme:@localhost:5500:acme'>
   <property name="foo" value="bar"/>
</native-data-source>

Additional data source configuration examples are shown in the article Data Source Configuration in Oracle Application Server 10g available at http://www.oracle.com/technology/tech/java/newsletter/articles/oc4j_datasource_config.html

Table 4-2 Native Data Source Settings

Application Server Control Console Property <managed-data- source> Attribute Description

Name

name

Required. The name of the data source. This must be a unique value.

JNDI Location

jndi-name

Required. The JNDI logical name for the data source object. OC4J binds an instance of the data source into the application JNDI namespace with this value.

Data Source Class

data-source-class

Required. The name and path of the data source class implementation. This must be an implementation of javax.sql.DataSource.

URL

url

Required. The URL that will be used by the JDBC driver to connect to the database. The URL typically identifies the database host machine, port, and database name. For example: jdbc:acme:@localhost:1234:acme

Login Timeout

login-timeout

The maximum time, in seconds, that this data source will wait while attempting to connect to a database. A value of 0 (zero) specifies that the timeout is the default system timeout if there is one; otherwise, it specifies that there is no timeout.

Optional. Default = 0.

User

user

The default user to use to connect to the data source.

Optional. No default.

Password

password

The default password to use to connect to the data source.

Optional. No default.


4.6.3 Connection Pools and Connection Factories

Path to Connection Factory and Connection Pool Settings

OC4J:Home > Administration tab > Task Name: Services > JDBC Resources: Go To Task > Connection Pools > Drill down to desired settings.

4.6.3.1 Connection Factories

The connection-factory tag defines the connection factory that will be used to create connections for the data source.

If the factory-class is an implementation of javax.sql.XADataSource, then the connections retrieved from this connection factory will be able to participate in global transactions and will NOT have their XA capabilities emulated. If the factory-class is not an implementation of javax.sql.XADatatSource, then the connections retrieved from this connection factory will emulate the XA behavior when participating in global transactions.

4.6.3.1.1 Connection Factory Properties

Each <connection-factory> tag can have zero or more <property> tags. Each <property> tag defines a property on the connection factory instance.

If the connection factory is an implementation of java.sql.Driver then each of these driver properties is placed in a java.util.Properties object that is used by the driver when it retrieves connections from the database.

If the connection factory is an implementation of javax.sql.DataSource, javax.sql.ConnectionPoolDataSource, or javax.sql.XADataSource, then reflection is used on the connection factory object to set the property's value.

The property name must match (case sensitive) the name of the setter method used to set the property. For example, if there exists on the connection factory object a property named MyProp, then a method named setMyProp() will be called to set the property. Therefore the property tag's name must be MyProp in order to set the property correctly.


Note:

It is possible to specify two different user/passwords in connection factory, one user/password in attributes and a different user/password in properties, as in the following example. In this case getConnection(), uses the user/password specified in the properties, in this example, scott2/tiger2, not the one specified in the attributes.

    <connection-factory user="scott1" password="tiger1" ...>
        <property name="user" value="scott2" />
        <property name="password" value="tiger2" />
    </connection-factory>


4.6.3.1.2 Connection Factory Proxy Interface

Each <connection-factory> tag may have zero or more <proxy-interface> tags.

Each proxy interface is implemented by a proxy that wraps the connection objects returned by the connection factory and the java.sql.* objects created by these connection objects.

The SQL Object setting defines the java.sql.* object for which the proxy interface is defined. This must be one of the following:

  • "Array"

  • "Blob"

  • "CallableStatement"

  • "Connection"

  • "DatabaseMetaData"

  • "ParameterMetaData"

  • "PreparedStatement"

  • "Ref"

  • "resultSet"

  • "ResultSetMetaData"

  • "Savepoint"

  • "SQLData"

  • "SQLInput"

  • "SQLOutput"

  • "Struct"

  • "Statement"

The interface attribute defines the fully qualified path of the interface that the proxy to this object will implement.

There may be more than one proxy interface defined for each SQL object.

The interface attribute defines the fully qualified path of the interface that the proxy to this object will implement.

There may be more than one proxy-interface tag defined for each SQL object.

The <xa-recover-config> tag defines the information needed for the transaction manager to perform recovery when a global transaction fails. The <username> sub tag defines the username used to perform the recovery. The <password> sub tag defines the password used to perform recovery.

4.6.3.2 Connection Properties

The <connection-properties> tag defines the connection properties that will be set on the connection factory when the connection factory is an instance of oracle.jdbc.pool.OracleDataSource (including instances that are derived from oracle.jdbc.pool.OracleDataSource). Each connection property is defined by the <property> sub-tag. There may be 0 - N <property> sub-tags defined for the <connection-properties> tag.

4.6.3.3 Connection Pools

A managed data source uses a connection pool to efficiently manage connections. If you will create managed data sources, you must define at least one connection pool and its connection factory.

The <connection-pool> tag defines one connection pool.

Each <connection-pool> tag must have one <connection-factory> tag.

Table 4-3 Connection Pool Attributes

Application Server Control Console Setting <connection-pool> Attribute Description

Name

name

Required. The name of the connection pool. This must be a unique value.

Minimum Number of Connections

min-connections

The minimum number of connections that the connection pool will maintain.

Optional. Default = 0.

The min-connections setting specifies the minimum number of connections that will be kept in the pool at any given time assuming the following activity:

  • There are no connections in use. If there are connections in use, then they are not in the pool, so there may be < min-connections> in the pool.

  • There have been sufficient connections created and were simultaneously in use such that the connection pool was required to create those connections.

For example, if min-connections is 10 and only 2 connections were ever used, then the number of connections available in the pool would be 2. OC4J will not create connections unnecessarily.

Maximum Number of Connections

max-connections

The maximum number of connections that the connection pool can contain.

A value of 0 indicates:

  • The data source connection pool is off. Connections are not pooled.

  • All other connection pool settings are ignored.

A negative value indicates that the connection pool is on and there is no maximum limit.

Optional. Default = No limit.

When the session starts, if max-connections is set lower than min-connections, then min-connections is reset to the value of max-connections.

Initial Size of Connection Cache

initial-limit

The size of the connection cache when the cache is initially created or reinitialized. When this property is set to a value greater than 0, that many connections are pre-created and are ready for use. This parameter is typically used to reduce the ramp-up time in priming the cache to its optimal size.

Optional. Default = 0.

When the initial-limit of a connection pool is greater than 1, but the user/password is not provided in the connection-factory, OC4J fails to start and throws an error. See the note after Table 4-4, "Connection Factory Attributes" .

When the session starts, if initial-limit is set greater than max-connections (for example, initial-limit=10 and max-connections=5), then only the max-connections number (5) of connections will be initialized.

When the session starts, if initial-limit is set less than min-connections, (for example, initial-limit=10 and min-connections=15), then only the initial-limit number (10) of connections will be initialized. Later on, when more connections are called, the min-connections number of connections will be maintained for the pool.

Wait for Used Connection Timeout

used-connection-wait-timeout

The amount of time to wait, in seconds, for a used connection to be released by a client.

This parameter only applies when the maximum number of connections has been retrieved from the data source and are in use. In this case when a client tries to borrow a connection from the pool and all connections are in use, the connection pool will wait for a connection to be released back to the pool.

Optional. Default = 0.

For a timeout setting to be enforced, the property-check-interval must be set lower than that timeout setting.

Inactivity Timeout

inactivity- timeout

The amount of time to wait, in seconds, that an unused connection may be inactive before it is removed from the pool.

Optional. Default = 60.

For a timeout setting to be enforced, the property-check-interval must be set lower than that timeout setting.

Login Timeout

login-timeout

The maximum amount of time, in seconds, that this data source will wait while attempting to connect to a database.

A value of 0 specifies that the timeout is the default system timeout if there is one; otherwise, it specifies that there is no timeout.

Optional. Default = 0.

For a timeout setting to be enforced, the property-check-interval must be set lower than that timeout setting.

Connection Retry Interval

connection-retry -interval

The interval to wait, in seconds, the before retrying a failed connection attempt.

This parameter is used in conjunction with max-connect-attempts.

Optional. Default = 1.

Maximum Connection Attempts

max-connect- attempts

The number of times to retry making a connection.

This parameter is used in conjunction with connection-retry-interval.

Optional. Default = 3.

Validate Connection

validate- connection

Oracle Implicit Connection Cache only.

Indicates whether or not a connection, when borrowed from the pool, will be validated against the database. Validation is performed by the SQL statement specified as the value of the validate-connection-statement parameter.

A value of true indicates that when a connection is borrowed from the connection pool, the SQL statement is executed to verify that the connection is valid.

Optional. Default = false, meaning that no validation is performed.

SQL Statement for Validation

validate- connection- statement

Oracle Implicit Connection Cache only.

If validate-connection is true, the SQL statement executed when a connection is borrowed from the pool.

Optional. No default.

Maximum Number of Statements Cached

num-cached- statements

The maximum number of SQL statements that should be cached for each connection. Any value greater than 0 automatically enables statement caching for the data source.

Optional. Default = 0.

For more detail, see "Setting the JDBC Statement Cache Size in Data Sources".

Max Active Time for a Used Connection

time-to-live-timeout

Oracle Implicit Connection Cache only.

The maximum time, in seconds, a used connection may be active.

When this timeout expires, the used connection is unconditionally closed, the relevant statement handles canceled, and the connection is returned to the connection pool.

Optional. Default = -1 means that the feature is not enabled.

For a timeout setting to be enforced, the property-check-interval must be set lower than that timeout setting.

Abandoned Connection Timeout

abandoned- connection- timeout

Oracle databases only.

The amount of time to wait, in seconds, that an unused logical connection may be inactive before it is removed from the pool.

This parameter is similar to inactivity-timeout, but on a logical connection borrowed from the cache by the user. When set, JDBC monitors SQL database activity on this logical connection.

For example, when a stmt.execute() is invoked on this connection, a heart beat is registered to convey that this connection is active. The heart beats are monitored only at places (to lower the cost of monitoring), that result in database execute calls.

If a connection has been inactive for the specified amount of time, the underlying PooledConnection is reclaimed and returned to the cache for reuse.

Optional. Default = -1, indicating that the feature is disabled.

For a timeout setting to be enforced, the property-check-interval must be set lower than that timeout setting.

Disable Server Connection Pooling (checkbox)

disable-server- connection- pooling

Whether or not to disable the application server's connection pool.

This parameter is provided because some JDBC drivers provide connection pooling inside the driver.

f the JDBC driver is Oracle and the driver is using the Implicit Connection Cache, then this parameter is ignored.

Optional. Default = false, indicating that the pool is enabled.

Enforce Timeout Limits Interval

property-check-interval

Oracle databases only.

Used with Oracle databases only. The time interval, in seconds, for the cache daemon thread to enforce the time out limits.

Optional. Default = 900.

For a timeout setting to be enforced, the property-check-interval must be set lower than that timeout setting.

Lower Threshold Limit On Pool

lower-threshold-limit

Oracle databases only.

Used with Oracle databases only. The lower threshold limit on the connection pool as a percentage of the value indicated in max-connections.

Optional. Default = 20 percent.


Table 4-4 lists and describes the connection factory attributes.

Table 4-4 Connection Factory Attributes

Application Server Control Console Setting <connection-factory> Attribute Description

Connection Factory Class

factory-class

Required. The name and path of the connection factory class that will be used to create connections for the data source. This class is provided by the JDBC driver. For example: com.acme.AcmeDataSource

This class must be an implementation of java.sql.Driver, javax.sql.DataSource, javax.sql.ConnectionPoolDataSource, or javax.sql.XADataSource.

If the factory-class is an implementation of javax.sql.XADataSource then the connections retrieved from this connection factory will be able to participate in global transactions and will NOT have their XA capabilities emulated. If the factory-class is not an implementation of javax.sql.XADatatSource then the connections retrieved from this connection factory will emulate the XA behavior when participating in global transactions.

URL

url

Required. The URL that will be used by the JDBC driver to connect to the database. The URL typically identifies the database host machine, port, and database name. For example: jdbc:acme:@localhost:1234:acme

User

user

The default user to use to connect to the database.

Optional. No default.

When the initial-limit of a connection-pool is greater than 1, but the user/password is not provided in the connection-factory, OC4J fails to start and throws an error. See the note after this table.

Password

password

The default password to use to connect to the database.

Optional. No default.

Login Timeout

login-timeout

The maximum amount of time, in seconds, that this data source will wait while attempting to connect to a database.

A value of 0 specifies that the timeout is the default system timeout if there is one; otherwise, it specifies that there is no timeout.

Optional. Default = 0.



Note:

When the initial-limit of a connection-pool is greater than 1, but the user/password is not provided in the connection-factory, OC4J fails to start and throws an error.

SEVERE: Error occurred initializing connectors. Exception is: Error creating data source connection pool. Exception: oracle.oc4j.sql.DataSourceException: Could not get/create instance of ConnectionCacheManager. Exception: User credentials doesn't match the existing ones com.evermind.server.ApplicationStateRunning initConnector

This error occurs because there is no user/password to initialize the connections in the pool.


4.6.3.3.1 Implicit Connection Cache

The Oracle Implicit Connection Cache (ICC) is a sophisticated connection pool that comes with the Oracle 10g JDBC driver. OC4J data sources automatically use the ICC. There is no additional configuration necessary to use the ICC.

Table 4-3, "Connection Pool Attributes" lists and describes the Connection Pool attributes. All of the connection pool attributes described in Table 4-3 apply to the Implicit Connection Cache (ICC), unless otherwise specified. Some of the attributes (identified) apply only to Implicit-Connection-Cache-enabled data sources (OracleDataSource and OracleXADataSource).

4.7 Configuration Examples

This section shows examples of data source definitions in the data-sources.xml configuration file.

The default application's data sources configuration file is located in $J2EE_HOME/config/data-sources.xml.

Each application can have its own data-sources.xml file. If an application has its own, then it is located in the root directory of the application.

This section contains the following information:

4.7.1 Syntax of the data-sources.xml File

Data source settings are persisted in an Enterprises Application's data-sources.xml file. Each <data-source> tag in this file represents one data source that is bound into JNDI and therefore accessible from client components (servlets, EJBs, etc.)

The following example describes the syntax of the data-sources.xml file. See the schema for details.

<managed-data-source
  attr1="val1"
  attr2="val2"
  …
/>

<native-data-source
  attr1="val1"
  attr2="val2"
  …>
      <property name="propertyName" value="propertyValue"/>
      …

</native-data-source>
<connection-pool
  attr1="val1"
  attr2="val2"
  …
>

      <connection-factory 
            attr1="val1"
            attr2="val2"
            …>

      <proxy-interface sql-object="javaSQLObject" interface=""/>
      …
      <property name="propertyName" value="propertyValue"/>
      …

      <xa-recover-config>
            <password-credential>
                  <username></username>
                  <password></password>
            </password-credential>
      </xa-recovery-config>

      <fatal-error-codes>
          <error-code code="integerCode"/>
          …
       </fatal-error-codes>
       <connection-properties>
          <property name="propertyName value="propertyValue"/>
         …
       </connection-properties>

   </connection-factory>
</connection-pool

Populated examples

The following example shows populated examples of the data-sources.xml definitions:

<?xml version="1.0" standalone="yes"?>
<data-sources>
   <connection-pool name="myConnectionPool" max-connections="30">
     <connection-factory 
       factory-class="oracle.jdbc.pool.OracleDataSource"
       user="scott"
       password="tiger"
      url="jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com"/>
     </connection-factory>
   </connection-pool>
  
   <managed-data-source
     jndi-name="jdbc/ManagedDS"
     name="Managed DataSource Name"
     connection-pool-name="myConnectionPool"/>

   <native-data-source
     name="nativeDataSource"
     jndi-name="jdbc/nativeDS"
     data-source-class="com.acme.DataSourceImpl"
     user="frank"
     password="frankpw"
     url="jdbc:acme:@localhost:5500:acme">
   </native-data-source>

</data-sources>

4.7.2 Examples: Configuring Data Sources

This section provides examples of data source configuration file definitions.

Additional data source configuration examples are shown in the article Data Source Configuration in Oracle Application Server 10g available at http://www.oracle.com/technology/tech/java/newsletter/articles/oc4j_datasource_config.html

4.7.2.1 Example: Native Data Source

<native-data-source 
    name='My Native DataSource'
    jndi-name='jdbc/nativeDs'
    data-source-class='com.acme.DataSourceImpl'
    user='frank'
    password='frankpw' 
    url='jdbc:acme:@localhost:5500:acme'>
        <property name="foo" value="bar"/>
</native-data-source>

4.7.2.2 Example: Managed Data Source Using an XADataSource Connection Factory

This data source does NOT emulate XA behavior. See "Emulating XA" for more information about emulating XA behavior.

<managed-data-source
    name='My Managed DataSource'
    jndi-name='jdbc/managedDs_1' 
    connection-pool-name='myConnectionPool'/>

<connection-pool 
    name='myConnectionPool'
    min-connections='5'
    max-connections='25'>
    <connection-factory
        factory-class='oracle.jdbc.xa.client.OracleXADataSource'
        user='scott'
        password='tiger'
        url='jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com'>
    </connection-factory>
</connection-pool>

4.7.2.3 Example: Managed Data Source Using a DataSource Connection Factory

This data source emulates XA behavior. See "Emulating XA" for more information about emulating XA behavior.

<managed-data-source
    name='My Managed DataSource'
    jndi-name='jdbc/managedDs_1' 
    connection-pool-name='myConnectionPool'/>

<connection-pool 
    name='myConnectionPool'
    min-connections='5'
    max-connections='25'>
    <connection-factory
        factory-class='oracle.jdbc.pool.OracleDataSource'
        user='scott'
        password='tiger'
        url='jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com'>
    </connection-factory>
</connection-pool>

4.7.2.4 Example: Managed Data Source Using a Driver Connection Factory

This data source emulates XA behavior. See "Emulating XA" for more information about emulating XA behavior.

<managed-data-source
    name='My Managed DataSource'
    jndi-name='jdbc/managedDs_1' 
    connection-pool-name='myConnectionPool'/>

<connection-pool 
    name='myConnectionPool'
    min-connections='5'
    max-connections='25'>
    <connection-factory
        factory-class='oracle.jdbc.OracleDriver'
        user='scott'
        password='tiger'
        url='jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com'>
    </connection-factory>
</connection-pool>

4.7.2.5 Example: Defining Proxy Interfaces

<connection-pool 
    name='myConnectionPool'
    min-connections='5'
    max-connections='25'>
    <connection-factory
        factory-class='oracle.jdbc.pool.OracleDataSource'
        user='scott'
        password='tiger'
        url='jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com'>
        <proxy-interface sql-object="Connection"
                       interface="oracle.jdbc.internal.OracleConnection"/>
        <proxy-interface sql-object="Statement"
                        interface="oracle.jdbc.OracleStatement"/>
        <proxy-interface sql-object="CallableStatement"
                        interface="oracle.jdbc.OracleCallableStatement"/>
        <proxy-interface sql-object="ResultSet"
                        interface="oracle.jdbc.OracleResultSet"/>
        <proxy-interface sql-object="PreparedStatement"
                        interface="oracle.jdbc.OraclePreparedStatement"/>
    </connection-factory>
</connection-pool>

4.7.2.6 Example: Defining XA Recovery

<connection-pool 
    name='myConnectionPool'
    min-connections='5'
    max-connections='25'>
    <connection-factory
        factory-class='oracle.jdbc.xa.client.OracleXADataSource'
        user='scott'
        password='tiger'
        url='jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com'>
        <xa-recovery-config>
            <password-credential>
                <username>system</username>
                <password>manager</password>
            </password-credential>
        </xa-recovery-config>
    </connection-factory>
</connection-pool>

4.7.2.7 Example: Connection Properties

<managed-data-source
   jndi-name="jdbc/managedDs_1"
   name="Managed DataSource"
   connection-pool-name="myConnectionPool"/>

<connection-pool
   name="myConnectionPool">
      <connection-factory 
            factory-class="oracle.jdbc.pool.OracleDataSource"
            user="scott"
            password="tiger" 
            url='jdbc:oracle:thin:@//localhost:1521/oracle.regress.rdbms.dev.us.oracle.com'>
            <connection-properties>
               <property name="oracle.jdbc.RetainV9LongBindBehavior" 
                  value="true"/>
            </connection-properties>
      </connection-factory>
</connection-pool>

For information on the connection properties, see "Connection Properties" .

4.7.3 Examples: Configuring Transaction Level

Global

Here's an example of configuring a managed data source for global transactions by setting the tx-level attribute to global in the data-sources.xml file.

<managed-data-source
   jndi-name="jdbc/ManagedDS"
   name="Managed DataSource Name"
   connection-pool-name="myConnectionPool"
   tx-level="global"/>

Local

Here's an example of configuring a managed data source for local transactions by setting the tx-level attribute to "local" in the data-sources.xml file. The default value is "global".

<managed-data-source
   jndi-name="jdbc/ManagedDS"
   name="Managed DataSource Name"
   connection-pool-name="myConnectionPool"
   tx-level="local"/>

4.7.4 Examples: Configuring Fast Connection Failover

The following is an example of configuring a connection factory for fast connection failover.

Thin

<connection-factory 
   factory-class="oracle.jdbc.pool.OracleDataSource"
   user="scott"
   password="tiger"
   url="jdbc:oracle:thin:@(DESCRIPTION=
(ADDRESS=(PROTOCOL=TCP)(HOST=cluster_alias) (PORT=1521))
 (CONNECT_DATA=(SERVICE_NAME=service_name)))"
          <property name="connectionCachingEnabled" value="true"/>
          <property name="fastConnectionFailoverEnabled" value="true"/>
</connection-factory>

OCI

The following is an example connection factory definition using OCI:

<connection-factory 
   factory-class="oracle.jdbc.pool.OracleDataSource"
   user="scott"
   password="tiger"
   url="jdbc:oracle:oci:@myAlias"
</connection-factory>

4.8 Using High Availability and Fast Connection Failover

OC4J's data sources are fully integrated with the Oracle 10G JDBC driver and therefore automatically take advantage of High Availability (HA) and Fast Connection Failover (FCF).

Additional High Availability and Fast Connection Failover information is available in the following documents:

Fast Connection Failover is a RAC/FaN client implemented in the JDBC Implicit connection cache. Its primary purpose is to guarantee the validity and availability of a connection. Hence Fast Connection Failover on the client side provides the following features:

To enable the Fast Connection Failover mechanism, the following properties and attributes must be set on the <connection-factory> tag for an OracleDataSource object.

Property Description
connectionCachingEnabled This is a Boolean property, and enables connection caching when set to true. By default connection caching is disabled and the property value is set to false.
fastConnectionFailoverEnabled This property, when set to TRUE, enables the Fast Connection Failover mechanism. By default, Fast Connection Failover is disabled and the property value is set to FALSE.
url This is an attribute on the <connection-factory> tag. When enabling Fast Connection Failover, the URL must be set using the service name syntax. The service name specified on the connection URL is used to map the connection cache to the service. If a SID is specified on the URL, when Fast Connection Failover is enabled, then an exception is thrown.

The following examples show valid and invalid syntax for URL usage on a connection cache setup for Fast Connection Failover.

Valid URL Usage

url="jdbc:oracle:oci:@TNS_ALIAS" 

url="jdbc:oracle:oci:@(DESCRIPTION= 
   (LOAD_BALANCE=on) 
   (ADDRESS=(PROTOCOL=TCP)(HOST=host1) (PORT=1521)) 
   (ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=1521)) 
   (CONNECT_DATA=(SERVICE_NAME=service_name)))" 

url="jdbc:oracle:oci:@(DESCRIPTION= 
   (ADDRESS=(PROTOCOL=TCP)(HOST=cluster_alias) (PORT=1521)) 
   (CONNECT_DATA=(SERVICE_NAME=service_name)))" 

url = "jdbc:oracle:thin@//host:port/service_name" 

url = "jdbc:oracle:thin@//cluster-alias:port/service_name" 

url="jdbc:oracle:thin:@(DESCRIPTION= 
   (LOAD_BALANCE=on) 
   (ADDRESS=(PROTOCOL=TCP)(HOST=host1) (PORT=1521)) 
   (ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=1521)) 
   (CONNECT_DATA=(SERVICE_NAME=service_name)))" 

url = "jdbc:oracle:thin:@(DESCRIPTION= 
   (ADDRESS=(PROTOCOL=TCP)(HOST=cluster_alias) (PORT=1521)) 
   (CONNECT_DATA=(SERVICE_NAME=service_name)))"

Invalid URL Usage

url = "jdbc:oracle:thin@host:port:SID"

Enabling Fast Connection Failover in the data-sources.xml File

The following example shows enabling fast connection failover for a Native Data Source in the data-sources.xml file:

<native-data-source> 
   name="nativeDataSource"
   jndi-name="jdbc/nativeDS"
   description="Native DataSource"
   data-source-class="oracle.jdbc.pool.OracleDataSource"
   user="scott"
   password="tiger"
   url="jdbc:oracle:thin:@localhost:1521:oracle">
  <property name="connectionCacheName" value="ICC1"/>
  <property name="connectionCachingEnabled" value="true"/>
  <property name="fastConnectionFailoverEnabled" value="false"/>
</native-data-source>

4.9 Using JDBC Drivers

This section discusses:

4.9.1 Oracle JDBC Drivers

This section has information about the Oracle JDBC OCI driver and the Oracle JDBC thin driver.

For more information about Oracle JDBC drivers, see the Oracle Database JDBC Developer's Guide and Reference.

4.9.1.1 OCI

The examples of Oracle data source definitions in this chapter use the Oracle JDBC Thin driver. However, you can use the Oracle JDBC OCI driver as well. Do the following before you start the OC4J server:

  1. Install the Oracle Client on the same system on which OC4J is installed.

  2. Set the OLE_HOME variable.

  3. Set LD_LIBRARY_PATH (or the equivalent environment variable for your OS) to $OLE_HOME/lib.

  4. Set TNS_ADMIN to a valid Oracle administration directory with a valid tnsnames.ora file.

The URL to use in the "url" attribute of the <connection-factory> element definition can have any of these forms:

  • jdbc:oracle:oci:@ This TNS entry is for a database on the same system as the client, and the client connects to the database in IPC mode.

  • jdbc:oracle:oci:@ TNS_service_name The TNS service name is an entry in the instance tnsnames.ora file.

  • jdbc:oracle:oci:@ full_TNS_listener_description For more TNS information, see the Oracle Net Administrator's Guide.

Here is an example connection factory definition using OCI:

<connection-factory 
    factory-class="oracle.jdbc.pool.OracleDataSource"
    user="scott"
    password="tiger"
    url="jdbc:oracle:oci:@myAlias"
</connection-factory>

4.9.1.2 Thin

The examples of Oracle data source definitions in this chapter use the Oracle JDBC Thin driver.

4.9.1.3 Notes on Oracle JDBC-OCI driver upgrade in the Oracle Application Server

It is not possible to upgrade to an arbitrary Oracle JDBC-OCI driver version due to client library compatibility constraints. Upgrading to OCI driver versions with matching Oracle Client libraries that are installed within the Oracle Application Server 10g (10.1.2) is supported. For example, Oracle JDBC 10.1.x drivers are supported, but the Oracle JDBC 9.2.x drivers are not.

Where the use of JDBC-OCI within the Oracle Application Server is supported, it is also necessary for the opmn.xml entry for each OC4J instance to propagate appropriate ORACLE_HOME and library path values to its startup environment.

The environment variable ORACLE_HOME is common to all platforms, but the name of the environment variable that specifies the library path is different depending on the operating systems:

  • LD_LIBRARY_PATH for Solaris

  • SLIB_PATH for AIX

  • SHLIB_PATH for HP-UX

  • PATH for Windows

The generic syntax for specifying the library paths in opmn.xml looks like this:

<prop name="<LIB_PATH_VARIABLE>" value="<LIB_PATH_VARIABLE_VALUE>"/>

where <LIB_PATH_VARIABLE> should be replaced with the appropriate platform-specific variable name that specifies the library path, and

<LIB_PATH_VARIABLE_VALUE>

should be replaced with that variable's value.

Here is an example, assuming the Solaris OS:

    <process-type id="OC4J_SECURITY" module-id="OC4J">
      <environment>
        <variable id="ORACLE_HOME"
  value="/u01/app/oracle/product/inf10120"/>
        <variable
          id="LD_LIBRARY_PATH"
          value="/u01/app/oracle/product/inf10120/lib"
        />
      </environment>
      ...
   

4.9.2 JDBC Drivers for non-Oracle Databases

When your application must connect to heterogeneous databases, use DataDirect JDBC drivers. DataDirect JDBC drivers are not meant to be used with an Oracle database but for connecting to non-Oracle databases, such as DB2, Sybase, Informix, and SQLServer. If you want to use DataDirect drivers with OC4J, then add corresponding entries for each database in the data-sources.xml file.

4.9.2.1 Installing and Setting Up DataDirect JDBC Drivers

Install the DataDirect JDBC drivers as described in the DataDirect Connect for JDBC User's Guide and Reference

After you have installed the drivers, follow these instructions to set them up.


Note:

In the following instructions, note these definitions:
  • OC4J_INSTALL: In a standalone OC4J environment, the directory into which you unzip the file oc4j_extended.zip. In an Oracle Application Server, OC4J_INSTALL is ORACLE_HOME.

  • In both a standalone OC4J environment and an Oracle Application Server, DDJD_INSTALL is the directory into which you unzip the content of the DataDirect JDBC drivers.

  • In a standalone OC4J environment, INSTANCE_NAME is home.

  • In an Oracle Application Server, INSTANCE_NAME is the OC4J instance into which you install the DataDirect JDBC drivers.


  1. Unzip the content of the DataDirect JDBC drivers to the directory DDJD_INSTALL.

  2. Create the directory OC4J_INSTALL/j2ee/INSTANCE_NAME/applib if it does not already exist.

  3. Copy the DataDirect JDBC drivers in DDJD_INSTALL/lib to the OC4J_INSTALL/j2ee/INSTANCE_NAME/applib directory.

  4. Verify that the file application.xml contains a library entry that references the j2ee/home/applib location, as follows:

    <library path="../../INSTANCE_NAME/applib" />
    
    
  5. Add data sources to the file data-source.xml as described in "Example DataDirect Data Source Entries".

4.9.2.2 Example DataDirect Data Source Entries

This section shows an example data source entry for each of the following non-Oracle databases:

You can also use vendor-specific data sources in the class attribute directly. That is, it is not necessary to use an OC4J-specific data source in the class attribute.

For more detailed information, refer to the DataDirect Connect for JDBC User's Guide and Reference.


Note:

OC4J does not work with non-Oracle data sources in the non-emulated case. That is, you cannot use a non-Oracle data source in a two-phase commit transaction.

Additional data source configuration examples are shown in the article Data Source Configuration in Oracle Application Server 10g available at http://www.oracle.com/technology/tech/java/newsletter/articles/oc4j_datasource_config.html

4.9.2.2.1 DataDirect DB2


Notes:

When using a DataDirect JDBC driver to connect to DB2, the following constraints apply:
  • This item is exceptional behavior:

    If you use com.oracle.ias.jdbcx.db2.DB2DataSource as the connection factory class, the <url> is a required element but the values passed in the url attributes are ignored. For this reason, setting the url alone is enough.

    In order for the data source to work properly, you must set the serverName, portNumber, and databaseName in <property> elements, even though the <property> tag is "technically" optional.

  • This item is normal behavior:

    If you use com.oracle.ias.jdbc.db2.DB2Driver as the connection factory class, then it is not necessary to set the serverName, portNumber, and databaseName in <property> elements. You can set the serverName, portNumber, and databaseName in the url attributes. The url is read completely and the values passed in the url attributes are read.


<managed-data-source 
   name="db2"
   jndi-name="jdbc/db2"
   connection-pool-name="db2 Connection Pool"/>

<connection-pool name="db2 Connection Pool">
    <connection-factory 
    factory-class="com.oracle.ias.jdbcx.db2.DB2DataSource"
    user="user1"
    password="user1"
                             
 url="jdbc:oracle:db2://localhost:50000;DatabaseName=sample;PackageName=JDBCPKG">
    <property name="databaseName" value="sample"/>
    <property name="packageName" value="JDBCPKG"/>
    <property name="serverName" value="localhost"/>
    <property name="portNumber" value="50000"/>
    <xa-recovery-config>
        <password-credential>
        <username>system</username>
        <password>manager</password>
         </password-credential>
    </xa-recovery-config>
    </connection-factory>
</connection-pool>

4.9.2.2.2 DataDirect Sybase

<managed-data-source
   name="Sybase"
   jndi-name="jdbc/Sybase"
   connection-pool-name="Sybase Connection Pool"/>

<connection-pool name=" Sybase Connection Pool">
    <connection-factory 
    factory-class="com.oracle.ias.jdbcx.sybase.SybaseDataSource"
    user="user1"
    password="password"
    url="jdbc:oracle:sybase://localhost:4101">
    <property name="serverName" value="localhost"/>
    <property name="portNumber" value="4101"/>
    <xa-recovery-config>
        <password-credential>
        <username>system</username>
        <password>manager</password>
        </password-credential>
    </xa-recovery-config>
    </connection-factory>
</connection-pool>

4.9.2.2.3 DataDirect Informix

<managed-data-source
   name="Informix"
   jndi-name="jdbc/Informix"
   connection-pool-name="Informix Connection Pool"/>

<connection-pool name=" Informix Connection Pool">
    <connection-factory 
    factory-class="com.oracle.ias.jdbc.informix.InformixDriver"
    user="user1"
    password="password"

    url="jdbc:oracle:informix://localhost:3900;informixServer=gtw93;DatabaseName=gatewaydb">

    <xa-recovery-config>
        <password-credential>
        <username>userid</username>
        <password>pword</password>
        </password-credential>
    </xa-recovery-config>
    </connection-factory>
</connection-pool>

4.9.2.2.4 DataDirect SQLServer

This section shows a SQLServer managed data source example and a SQLServer native source example.

SQLServer Managed Data Source

  <connection-pool name="ConnectionSqlserver" 
                 max-connections="20" 
                 min-connections="1"> 
        <connection-factory 
factory-class="com.oracle.ias.jdbcx.sqlserver.SQLServerDataSource" 
                 user="msuser" 
                 password="mspass" 
                  
url="jdbc:oracle:sqlserver://myserver\\myinstance;User=msuser;Password=mspass" > 
             <property name="serverName" value="myserver\\myinstance"/> 
             <xa-recovery-config> 
                  <password-credential> 
                       <username>msuser</username> 
                       <password>mspass</password> 
                  </password-credential> 
             </xa-recovery-config> 
        </connection-factory> 
    </connection-pool> 
. 
    <managed-data-source connection-pool-name="ConnectionSqlserver" 
                         jndi-name="jdbc/mysqlserver" 
                         name="mysqlserver" /> 

SQLServer Native Data Source

    <native-data-source 
           jndi-name="jdbc/mysqlserver" 
           name="mysqlserver" 
            
data-source-class="com.oracle.ias.jdbcx.sqlserver.SQLServerDataSource" 
           user="msuser" 
           password="mspass" 
            
url="jdbc:oracle:sqlserver://myserver\\myinstance;User=msuser;Password=mspass" > 
             <property name="serverName" value="myserver\\myinstance"/> 
    </native-data-source> 

4.9.2.3 Additional Data Source Configuration Examples

The following additional data source configuration examples show various permutations of data source type, connection factory type, and other variables. These examples are taken from the article Data Source Configuration in Oracle Application Server 10g available at http://www.oracle.com/technology/tech/java/newsletter/articles/oc4j_datasource_config.html

Native Data Source - Oracle JDBC to Oracle Database

<native-data-source
  name="nativeDataSource"
  jndi-name="jdbc/nativeDS"
  description="Native DataSource"
  data-source-class="oracle.jdbc.pool.OracleDataSource"
  user="scott"
  password="tiger"
  url="jdbc:oracle:thin:@//dbhost:1521/dbservicename">
</native-data-source>

Native Data Source - DataDirect JDBC to DB2 UDB

<native-data-source
  name="nativeDataSource"
  jndi-name="jdbc/nativeDS"
  description="Native DataSource"
  data-source-class="com.ddtek.jdbcx.db2.DB2DataSource"
  user="frank"
  password="frankpw"
  url="jdbc:datadirect:db2://server_name:50000;DatabaseName=your_database">
</native-data-source>

Native Data Source - DB2 Universal JDBC to DB2 UDB

<native-data-source
  name="nativeDataSource"
  jndi-name="jdbc/nativeDS"
  description="Native DataSource"
  data-source-class="com.ibm.db2.jcc.DB2DataSource"
  user="db2adm"
  password="db2admpwd"
  url="jdbc:db2://sysmvs1.stl.ibm.com:5021/dbname:user=db2adm;password=db2admpwd;">
</native-data-source>

Managed Data Source Using an XADataSource Connection Factory

<managed-data-source
  jndi-name="jdbc/ManagedDS"
  description="Managed DataSource"
  connection-pool-name="myConnectionPool"/>

<connection-pool
  name="myConnectionPool"
  min-connections="10"
  max-connections="30"
  inactivity-timeout="30">
    <connection-factory 
        factory-class="oracle.jdbc.xa.client.OracleXADataSource"
        user="scott"
        password="tiger"
        url="jdbc:oracle:thin:@//dbhost:1521/dbservicename"/>
    </connection-factory>
</connection-pool>

Managed Data Source Using a DataSource Connection Factory

<managed-data-source
  jndi-name="jdbc/ManagedDS"
  description="Managed DataSource">
  connection-pool-name="myConnectionPool"/>

<connection-pool
  name="myConnectionPool"
  min-connections="10"
  max-connections="30"
  inactivity-timeout="30">
    <connection-factory 
        factory-class="oracle.jdbc.pool.OracleDataSource"
        user="scott"
        password="tiger"
        url="jdbc:oracle:thin:@//dbhost:1521/dbservicename"/>
    </connection-factory>
</connection-pool>

Managed Data Source Using a Driver Connection Factory

<managed-data-source
  jndi-name="jdbc/ManagedDS"
  description="Managed DataSource">
  connection-pool-name="myConnectionPool"/>

<connection-pool
  name="myConnectionPool"
  min-connections="10"
  max-connections="30"
  inactivity-timeout="30">
    <connection-factory 
        factory-class="oracle.jdbc.OracleDriver"
        user="scott"
        password="tiger"
        url="jdbc:oracle:thin:@//dbhost:1521/dbservicename"/>
    </connection-factory>
</connection-pool>

4.10 Legacy Configuration

The following points are pertinent for the configuration of versions prior to 10.1.3: