3.3.6 Implementation for connecting to the resources

To connect from the application to a resource, the resource references must be obtained for Enterprise Beans and servlets. The methods of obtaining the resource references include the method of using lookup and the method of using DI (Dependency Injection).

Note that when using EJB 3.0 or later, use DI to obtain the resource references.

Organization of this subsection
(1) Method of obtaining the resource references by using lookup
(2) Method of obtaining the resource references by using the DI
(3) Notes on connecting to the resources

(1) Method of obtaining the resource references by using lookup

When you want to use the lookup method, connect the application to the resource as follows:

  1. Use the JNDI to look up the factory class that is used for obtaining the connection to the resource.
    Specify the name to be looked up using the DD of Enterprise Beans and servlets. The applicable tag is the <res-ref-name> tag in the <resource-ref> tag.
  2. Use the connection factory class to obtain the connection.
  3. Use the obtained connection to connect to the resource.
  4. Close the used connection.

If you use connection pooling, a pooled connection is obtained in step 2 and the connection is returned to the pool in step 4. The user program does not require a connection pooling-aware coding.

(2) Method of obtaining the resource references by using the DI

To use the DI for obtaining the resource references, the DD definitions are unnecessary. For an overview of the DI and the notes on DI usage, see 12.4 Using the DI.

(3) Notes on connecting to the resources

If you obtain a resource connection through a user program, make sure you close the connection after use. Specifically, close the connection using the finally clause so that the connection is definitely closed even when an exception occurs.

Note that the time when the finalize method is invoked depends on the timing of JavaVM garbage collection, so do not specify the design of using the finalize method to close the connection. If a connection is not closed properly through the user program, the maximum number of connections that can be obtained is reached and you might not be able to obtain more connections.