6.6. Access to SQL Connections

Kodo JDO provides two mechanisms for obtaining a java.sql.Connection object. This can be useful when direct access to the underlying data store is required.

The following code obtains the connection that is currently in use by a particular PersistenceManager. If there is no connection open to the data store for the given thread, then a new one is created and returned. If a data store transaction is in progress, then the connection returned will be transactionally consistent. See the Javadoc for com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager for more details.

The setting of the com.solarmetric.kodo.impl.jdbc.ConnectionRetainMode property has an impact on the semantics of this method. If the property is set to on-demand (the default) and an optimistic transaction is in progress, then the connections returned by this method will be freshly retrieved from the pool, and may not be the same as the one upon which the transaction will eventually commit. If it's set to transaction or persistence-manager, then it will be used for the duration of the transaction.

Example 6.1. Obtaining a java.sql.Connection object from the PersistenceManager

PersistenceManagerFactory factory = ...; // obtain a PersistenceManagerFactory
PersistenceManagerImpl pm = 
  (PersistenceManagerImpl) factory.getPersistenceManager ();
JDBCStoreManager storeManager = (JDBCStoreManager) pm.getStoreManager ();
Connection conn = storeManager.getConnection ();

// do stuff

storeManager.releaseConnection (conn);
The connection returned can safely be released regardless of the current transactional state, and regardless of whether or not the PersistenceManager is being closed. Releasing the connection does not close the connection unless appropriate.

Additionally, a connection that is in no way linked to the current PersistenceManager can be obtained using Kodo JDO:

PersistenceManagerFactory factory = ...;
DataSource dataSource = (DataSource) factory.getConnectionFactory ();
Connection conn = dataSource.getConnection ();
Note that for this example, it is up to you to do all cleaning up. Additionally, you may need to enter a username and password when obtaining a connection from the DataSource, depending on how you created the PersistenceManagerFactory.