bea.com | products | dev2dev | support | askBEA
 Download Docs   Site Map   Glossary 
Search

Programming WebLogic JDBC

 Previous Next Contents View as PDF  

Configuring and Administering WebLogic JDBC

You use WebLogic Server Administration Console to enable, configure, and monitor features of the WebLogic Server, including JDBC.

The following sections describe how to program the JDBC connectivity components:

For additional information, see

 


Configuring and Using Connection Pools

A connection pool is a named group of identical JDBC connections to a database that are created when the connection pool is registered, either at WebLogic Server startup or dynamically during run time. Your application "borrows" a connection from the pool, uses it, then returns it to the pool by closing it. Also see Overview of Connection Pools.

Advantages to Using Connection Pools

Connection pools provide numerous performance and application design advantages:

The attributes for a configuring a connection pool are defined in the Administration Console Online Help. There is also an API that you can use to programmatically create connection pools in a running WebLogic Server; see Creating a Connection Pool Dynamically. You can also use the command line; see the Web Logic Server Command-Line Interface Reference .

Creating a Connection Pool at Startup

To create a startup (static) connection pool, you define attributes and permissions in the Administration Console before starting WebLogic Server. WebLogic Server opens JDBC connections to the database during the startup process and adds the connections to the pool.

To configure a connection pool in the Administration Console, in the navigation tree in the left pane, expand the Services and JDBC nodes, then select Connection Pool. The right pane displays a list of existing connection pools. Click the Configure a new JDBC Connection Pool text link to create a connection pool.

For step-by-step instructions and a description of connection pool attributes, see the Administration Console Online Help, available when you click the question mark in the upper-right corner of the Administration Console.

Avoiding Server Lockup with the Correct Number of Connections

When your applications attempt to get a connection from a connection pool in which there are no available connections, the connection pool throws an exception stating that a connection is not available in the connection pool. Connection pools do not queue requests for a connection. To avoid this error, make sure your connection pool can expand to the size required to accommodate your peak load of connection requests.

To set the maximum number of connections for a connection pool in the Administration Console, expand the navigation tree in the left pane to show the Services—>JDBC—>Connection Pools nodes and select a connection pool. Then, in the right pane, select the Configuration—>Connections tab and specify a value for Maximum Capacity.

Database Passwords in Connection Pool Configuration

When you create a connection pool, you typically include at least one password to connect to the database. If you use an open string to enable XA, you may use two passwords. You can enter the passwords as a name-value pair in the Properties field or you can enter them in their respective fields:

If you specify a password in the Properties field when you first configure the connection pool, WebLogic Server removes the password from the Properties string and sets the value as the Password value in an encrypted form the next time you start WebLogic Server. If there is already a value for the Password attribute for the connection pool, WebLogic Server does not change any values. However, the value for the Password attribute overrides the password value in the Properties string. The same behavior applies to any password that you define as part of an open string. For example, if you include the following properties when you first configure a connection pool:

user=scott;
password=tiger;
openString=Oracle_XA+Acc=p/scott/tiger+SesTm=177+db=jtaXaPool+Threads=true+Sqlnet=lcs817+logDir=.+dbgFl=0x15;server=lcs817

The next time you start WebLogic Server, it moves the database password and the password included in the open string to the Password and Open String Password attributes, respectively, and the following value remains for the Properties field:

user=scott;
openString=Oracle_XA+Acc=p/scott/+SesTm=177+db=jtaXaPool+Threads=true+Sqlnet=lcs817+logDir=.+dbgFl=0x15;server=lcs817

After a value is established for the Password or Open String Password attributes, the values in these attributes override the respective values in the Properties attribute. That is, continuing with the previous example, if you specify tiger2 as the database password in the Properties attribute, WebLogic Server ignores the value and continues to use tiger as the database password, which is the current encrypted value of the Password attribute. To change the database password, you must change the Password attribute.

Note: The value for Password and Open String Password do not need to be the same.

Creating a Connection Pool Dynamically

The JDBCConnectionPool administration MBean as part of the WebLogic Server management architecture (JMX). You can use the JDBCConnectionPool MBean to create and configure a connection pool dynamically from within a Java application. That is, from your client or server application code, you can create a connection pool in a WebLogic Server that is already running.

You can also use the CREATE_POOL command in the WebLogic Server command line interface to dynamically create a connection pool. See CREATE_POOL.

To dynamically create a connection pool using the JDBCConnectionPool administration MBean, follow these main steps:

  1. Import required packages.
  2. Look up the administration MBeanHome in the JNDI tree.
  3. Get the server MBean.
  4. Create the connection pool MBean.
  5. Set the properties for the connection pool.
  6. Add the target.
  7. Create a DataSource object.

Note: Dynamically created connection pools must use dynamically created DataSource objects. For a DataSource to exist, it must be associated with a connection pool. Also, a one-to-one relationship exists between DataSource objects and connection pools in WebLogic Server. Therefore, you must create a DataSource to use with a connection pool.

When you create a connection pool using the JDBCConnectionPool MBean, the connection pool is added to the server configuration and will be available even if you stop and restart the server. If you do not want the connection pool to be persistent, you must remove it programmatically.

Also, you can temporarily disable dynamically created connection pools, which suspends communication with the database server through any connection in the pool. When a disabled pool is re-enabled, each connection returns to the same state as when the pool was disabled; clients can continue their database operations exactly where they left off.

For more information about using MBeans to manage WebLogic Server, see Programming WebLogic Management Services with JMX. For more information about the JDBCConnectionPool MBean, see the Javadoc at.

Dynamic Connection Pool Sample Code

The following sections show code samples for performing the main steps to create a connection pool dynamically.

Import Packages

import java.sql.*;
import java.util.*;
import javax.naming.Context;
import javax.sql.DataSource;
import weblogic.jndi.Environment;
import weblogic.management.configuration.JDBCConnectionPoolMBean;
import weblogic.management.runtime.JDBCConnectionPoolRuntimeMBean;
import weblogic.management.configuration.JDBCDataSourceMBean;
import weblogic.management.configuration.ServerMBean;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicObjectName;

Look Up the Administration MBeanHome

mbeanHome = (MBeanHome)ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);

Get the Server MBean

serverMBean = (ServerMBean)mbeanHome.getAdminMBean(serverName, "Server");
//Create a WebLogic object name for the Server MBean
//to use to create a name for the JDBCConnectionPoolRuntime MBean.
WebLogicObjectName pname = new WebLogicObjectName("server1", "ServerRuntime", mbeanHome.getDomainName(),"server1");
//Create a WebLogic object name for the JDBCConnectionPoolRuntime MBean
//to use to create or get the JDBCConnectionPoolRuntime MBean.
WebLogicObjectName oname = new WebLogicObjectName(cpName, "JDBCConnectionPoolRuntime", mbeanHome.getDomainName(),"server1", pname);
JDBCConnectionPoolRuntimeMBean cprmb = (JDBCConnectionPoolRuntimeMBean)mbeanHome.getMBean(oname);

Create the Connection Pool MBean

  // Create ConnectionPool MBean
cpMBean = (JDBCConnectionPoolMBean)mbeanHome.createAdminMBean(
cpName, "JDBCConnectionPool",
mbeanHome.getDomainName());

Set the Connection Pool Properties

  Properties pros = new Properties();
pros.put("user", "scott");
pros.put("server", "lcdbnt1");
  // Set DataSource attributes
cpMBean.setURL("jdbc:weblogic:oracle");
cpMBean.setDriverName("weblogic.jdbc.oci.Driver");
cpMBean.setProperties(pros);
cpMBean.setPassword("tiger");
cpMBean.setLoginDelaySeconds(1);
cpMBean.setInitialCapacity(1);
cpMBean.setMaxCapacity(10);
cpMBean.setCapacityIncrement(1);
cpMBean.setShrinkingEnabled(true);
cpMBean.setShrinkPeriodMinutes(10);
cpMBean.setRefreshMinutes(10);
cpMBean.setTestTableName("dual");

Note: In this example, the database password is set using the setPassword(String) method instead of including it with the user and server names in Properties. When you use the setPassword(String) method, WebLogic Server encrypts the password in the config.xml file and when displayed on the administration console. BEA recommends that you use this method to avoid storing database passwords in clear text in the config.xml file.

Add the Target

  cpMBean.addTarget(serverMBean);

Create a DataSource

public void createDataSource() throws SQLException {
try {
// Get context
Environment env = new Environment();
env.setProviderUrl(url);
env.setSecurityPrincipal(userName);
env.setSecurityCredentials(password);
ctx = env.getInitialContext();
      // Create DataSource  MBean
dsMBeans = (JDBCDataSourceMBean)mbeanHome.createAdminMBean(
cpName, "JDBCDataSource",
mbeanHome.getDomainName());
      // Set DataSource attributes
dsMBeans.setJNDIName(cpJNDIName);
dsMBeans.setPoolName(cpName);
      // Startup datasource
dsMBeans.addTarget(serverMBean);
    } catch (Exception ex) {
ex.printStackTrace();
throw new SQLException(ex.toString());
    }
  }

Removing a Dynamic Connection Pool and DataSource

The following code sample shows how to remove a dynamically created connection pool. If you do not remove dynamically created connection pools, they will remain available even after the server is stopped and restarted.

public void deleteConnectionPool() throws SQLException {
try {
// Remove dynamically created connection pool from the server
cpMBean.removeTarget(serverMBean);
// Remove dynamically created connection pool from the configuration
mbeanHome.deleteMBean(cpMBean);
} catch (Exception ex) {
throw new SQLException(ex.toString());
}
}
  public void deleteDataSource() throws SQLException {
    try {
      // Remove dynamically created datasource from the server
      dsMBeans.removeTarget(serverMBean);
      // Remove dynamically created datasource from the configuration
      mbeanHome.deleteMBean(dsMBeans);
    } catch (Exception ex) {
      throw new SQLException(ex.toString());
    }
  }

Managing Connection Pools

Note: Many methods described in this section have been updated with the latest release of WebLogic Server. See the related Javadocs for updated information:

New methods include:

The JDBCConnectionPool and JDBCConnectionPoolRuntime MBeans provide methods to manage connection pools and obtain information about them. Methods are provided for:

The JDBCConnectionPool and JDBCConnectionPoolRuntime MBeans replace the weblogic.jdbc.common.JdbcServices and weblogic.jdbc.common.Pool classes, which are deprecated.

For more information about methods provided by the JDBCConnectionPoolMBean, see the Javadoc. For more information about the methods provided by the JDBCConnectionPoolRuntimeMBean, see the Javadoc.

Retrieving Information About a Pool

boolean x = JDBCConnectionPoolRuntimeMBean.poolExists(cpName);
props = JDBCConnectionPoolRuntimeMBean.getProperties();

The poolExists() method tests whether a connection pool with a specified name exists in the WebLogic Server. You can use this method to determine whether a dynamic connection pool has already been created or to ensure that you select a unique name for a dynamic connection pool you want to create.

The getProperties() method retrieves the properties for a connection pool.

Disabling a Connection Pool

JDBCConnectionPoolRuntimeMBean.disableDroppingUsers()

JDBCConnectionPoolRuntimeMBean.disableFreezingUsers()

JDBCConnectionPoolRuntimeMBean.enable()

You can temporarily disable a connection pool, preventing any clients from obtaining a connection from the pool. Only the "system" user or users granted "admin" permission by an ACL associated with a connection pool can disable or enable the pool.

After you call disableFreezingUsers(), clients that currently have a connection from the pool are suspended. Attempts to communicate with the database server throw an exception. Clients can, however, close their connections while the connection pool is disabled; the connections are then returned to the pool and cannot be reserved by another client until the pool is enabled.

Use disableDroppingUsers() to not only disable the connection pool, but to destroy the client's JDBC connection to the pool. Any transaction on the connection is rolled back and the connection is returned to the connection pool. The client's JDBC connection context is no longer valid.

When a pool is enabled after it has been disabled with disableFreezingUsers(), the JDBC connection states for each in-use connection are exactly as they were when the connection pool was disabled; clients can continue JDBC operations exactly where they left off.

You can also use the disable_pool and enable_pool commands of the weblogic.Admin class to disable and enable a pool.

Shrinking a Connection Pool

JDBCConnectionPoolRuntimeMBean.shrink()

A connection pool has a set of properties that define the initial and maximum number of connections in the pool (initialCapacity and maxCapacity), and the number of connections added to the pool when all connections are in use (capacityIncrement). When the pool reaches its maximum capacity, the maximum number of connections are opened, and they remain opened unless you shrink the pool.

You may want to drop some connections from the connection pool when a peak usage period has ended, freeing up WebLogic Server and DBMS resources.

Shutting Down a Connection Pool

JDBCConnectionPoolRuntimeMBean.shutdownSoft()

JDBCConnectionPoolRuntimeMBean.shutdownHard()

These methods destroy a connection pool. Connections are closed and removed from the pool and the pool dies when it has no remaining connections. Only the "system" user or users granted "admin" permission by an ACL associated with a connection pool can destroy the pool.

The shutdownSoft() method waits for connections to be returned to the pool before closing them.

The shutdownHard() method kills all connections immediately. Clients using connections from the pool get exceptions if they attempt to use a connection after shutdownHard() is called.

You can also use the destroy_pool command of the weblogic.Admin class to destroy a pool.

Resetting a Pool

JDBCConnectionPoolRuntimeMBean.reset()

You can configure a connection pool to test its connections either periodically, or every time a connection is reserved or released. Allowing the WebLogic Server to automatically maintain the integrity of pool connections should prevent most DBMS connection problems. In addition, WebLogic provides methods you can call from an application to refresh all connections in the pool or a single connection you have reserved from the pool.

The JDBCConnectionPoolRuntimeMBean.reset() method closes and reopens all allocated connections in a connection pool. This may be necessary after the DBMS has been restarted, for example. Often when one connection in a connection pool has failed, all of the connections in the pool are bad.

Use any of the following means to reset a connection pool:

$ java weblogic.Admin WebLogicURL RESET_POOL poolName system passwd

You might use this method from the command line on an infrequent basis. There are more efficient programmatic ways that are also discussed here.

Using weblogic.jdbc.common.JdbcServices and weblogic.jdbc.common.Pool Classes (Deprecated)

Previous versions of WebLogic Server included classes that you could use to programmatically create and manage connection pools: weblogic.jdbc.common.JdbcServices and weblogic.jdbc.common.Pool. These classes are now deprecated. Although these classes are still available, BEA recommends that you use the JDBCConnectionPool MBean instead of these classes to dynamically create and manage connection pools.

When you use the JDBCConnectionPool MBean to create or modify a connection pool on a managed server, the JMX service immediately notifies the administration server of the change. When you use weblogic.jdbc.common.JdbcServices and weblogic.jdbc.common.Pool to create or modify a connection pool, the following actions are not conveyed to the Administration Server:

After any of these actions, applications on managed servers that use the affected connection pool may fail.

For more information about weblogic.jdbc.common.JdbcServices and weblogic.jdbc.common.Pool, see "Configuring WebLogic JDBC Features" in Programming WebLogic JDBC for WebLogic Server 6.1.

 


Application-Scoped JDBC Connection Pools

When you package your enterprise applications, you can include the weblogic-application.xml supplemental deployment descriptor, which you use to configure application scoping. Within the weblogic-application.xml file, you can configure JDBC connection pools that are created when you deploy the enterprise application.

An instance of the connection pool is created with each instance of your application. This means an instance of the pool is created with the application on each node that the application is targeted to. It is important to keep this in mind when considering pool sizing.

Connection pools created in this manner are known as application-scoped connection pools, app scoped pools, application local pools, app local pools, or local pools, and are scoped for the enterprise application only. That is, they are isolated for use by the enterprise application.

For more information about application scoping and application scoped resources, see:

 


Configuring and Using MultiPools

A MultiPool is a "pool of pools." MultiPools contain a configurable algorithm for choosing which connection pool will return a connection to the client.

You create a MultiPool by first creating connection pools, then creating the MultiPool using the Administration Console or WebLogic Management API and assigning the connection pools to the MultiPool.

For more information about MultiPools, see the Administration Console Online Help. For information about the JDBCMultiPoolMBean, see the WebLogic Server Javadocs.

MultiPool Features

A MultiPools is a pool of connection pools in a single server. All the connections in a particular connection pool are created identically with a single database, single user, and the same connection attributes; that is, they are attached to a single database. However, the connection pools within a MultiPool may be associated with different users or DBMSs.

MultiPools are used in local transactions and are not supported by WebLogic Server for distributed transactions.

Choosing the MultiPool Algorithm

Before you set up a MultiPool, you need to determine the primary purpose of the MultiPool—high availability or load balancing. You can choose the algorithm that corresponds with your requirements.

Note: Capacity is not a failover reason, because users have the right to set capacity. MultiPools take effect only if loss of database connectivity has occurred.

High Availability

The High Availability algorithm provides an ordered list of connection pools. Normally, every connection request to this kind of MultiPool is served by the first pool in the list. If a database connection via that pool fails, then a connection is sought sequentially from the next pool on the list.

Load Balancing

Connection requests to a load balancing MultiPool are served from any connection pool in the list. Pools are added without any attached ordering and are accessed using a round-robin scheme. When switching connections, the connection pool just after the last pool accessed is selected.

Messages and Error Conditions

Users may request information regarding the connection pool from which the connection originated.

Exceptions

Entries are posted to the JDBC log under these circumstances:

Capacity Issues

In a high availability scenario, the fact that the first pool in the list is busy (all connections are being used) does not trigger an attempt to get a connection from the next pool in the list.

 


Configuring and Using DataSources

As with Connection Pools and MultiPools, you can create DataSource objects in the Administration Console or using the WebLogic Management API. DataSource objects can be defined with or without transaction services. You configure connection pools and MultiPools before you define the pool name attribute for a DataSource.

DataSource objects, along with the JNDI, provide access to connection pools for database connectivity. Each DataSource can refer to one connection pool or MultiPool. However, you can define multiple DataSources that use a single connection pool. This allows you to define both transaction and non-transaction-enabled DataSource objects that share the same database.

WebLogic Server supports two types of DataSource objects:

If your application meets any of the following criteria, you should use a TxDataSource in WebLogic Server:

If you want applications to use a DataSource to get a database connection from a connection pool (the preferred method), you should define the DataSource in the Administration Console before running your application. For more information about how to configure a DataSource and when to use a TxDataSource, see JDBC DataSources.

Importing Packages to Access DataSource Objects

To use the DataSource objects in your applications, import the following classes in your client code:

import java.sql.*;
import java.util.*;
import javax.naming.*;

Obtaining a Client Connection Using a DataSource

To obtain a connection from a JDBC client, use a Java Naming and Directory Interface (JDNI) lookup to locate the DataSource object, as shown in this code fragment:

Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,
"t3://hostname:port");
  try {
ctx = new InitialContext(ht);
javax.sql.DataSource ds
= (javax.sql.DataSource) ctx.lookup ("myJtsDataSource");
java.sql.Connection conn = ds.getConnection();
// You can now use the conn object to create 
// Statements and retrieve result sets:
Statement stmt = conn.createStatement();
stmt.execute("select * from someTable");
ResultSet rs = stmt.getResultSet();
// Close the statement and connection objects when you are finished:
   stmt.close();
conn.close();
}
catch (NamingException e) {
// a failure occurred
}
finally {
try {ctx.close();}
catch (Exception e) {
// a failure occurred
}
}
(Substitute the correct hostname and port number for your WebLogic Server.)

Note: The code above uses one of several available procedures for obtaining a JNDI context. For more information on JNDI, see Programming WebLogic JNDI.

Code Examples

See the DataSource code example in the samples/examples/jdbc/datasource directory of your WebLogic Server installation.

JDBC Data Source Factories

In WebLogic Server, you can bind a JDBC DataSource resource into the WebLogic Server JNDI tree as a resource factory. You can then map a resource factory reference in the EJB deployment descriptor to an available resource factory in a running WebLogic Server to get a connection from a connection pool.

For details about creating and using a JDBC Data Source factory, see Resource Factories in Programming WebLogic Enterprise JavaBeans.

 

Back to Top Previous Next