4.9. Runtime Access to JDBC Connections

Kodo JDO provides two mechanisms for obtaining a java.sql.Connection object. Accessing a connection can be useful when you require direct access to the underlying data store.

The following code obtains the connection that is currently in use by a particular persistence manager. If there is no connection open to the data store for the persistence manager, then a new one is created and returned. If a data store transaction is in progress, then the connection returned will be transactionally consistent.

[Note]Note

Whether or not a persistence manager already has a connection open at any point in time is determined by whether a transaction is in progress, the type of the transaction (optimistic or datastore), and the setting of the kodo.ConnectionRetainMode property. It can also be influenced by whether or not you have explicitly flushed transactional changes, and the value of the kodo.FlushBeforeQueries property.

Example 4.9. Obtaining a JDBC Connection from the PersistenceManager

import java.sql.*;
import kodo.runtime.*;

...

KodoPersistenceManager kpm = (KodoPersistenceManager) pm;
Connection conn = (Connection) kpm.getConnection ();

// do stuff

conn.close ();

The connection should be closed regardless of the current transactional state, and regardless of whether or not the persistence manager is being closed. The connection returned from the KodoPersistenceManager will ignore close invocations as needed to maintain transactional integrity.

Additionally, you can request a connection that is independent of the current persistence manager:

Example 4.10. Obtaining a JDBC Connection from the DataSource

import java.sql.*;
import javax.sql.*;
import kodo.conf.*;
import kodo.runtime.*;

...

KodoPersistenceManager kpm = (KodoPersistenceManager) pm;
JDOConfiguration conf = kpm.getConfiguration ();
DataSource dataSource = (DataSource) conf.getConnectionFactory ();
Connection conn = dataSource.getConnection ();

// do stuff

conn.close ();