4.3. Runtime Access to DataSource

The JPA standard defines how to access JDBC connections from enterprise beans. Kodo also provides APIs to access an EntityManager's connection, or to retrieve a connection directly from the EntityManagerFactory's DataSource.

The OpenJPAEntityManager.getConnection method returns an EntityManager's connection. If the EntityManager does not already have a connection, it will obtain one. The returned connection is only guaranteed to be transactionally consistent with other EntityManager operations if the EntityManager is in a managed or non-optimistic transaction, if the EntityManager has flushed in the current transaction, or if you have used the OpenJPAEntityManager.beginStore method to ensure that a datastore transaction is in progress. Always close the returned connection before attempting any other EntityManager operations. Kodo will ensure that the underlying native connection is not released if a datastore transaction is in progress.

Example 4.4. Using the EntityManager's Connection

import java.sql.*;
import org.apache.openjpa.persistence.*;

...

OpenJPAEntityManager oem = OpenJPAPersistence.cast (em);
Connection conn = (Connection) oem.getConnection ();

// do JDBC stuff

conn.close ();

The example below shows how to use a connection directly from the DataSource, rather than using an EntityManager's connection.

Example 4.5. Using the EntityManagerFactory's DataSource

import java.sql.*;
import javax.sql.*;
import kodo.conf.*;
import org.apache.openjpa.persistence.*;

...

OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast (emf);
OpenJPAConfiguration conf = oemf.getConfiguration ();
DataSource dataSource = (DataSource) conf.getConnectionFactory ();
Connection conn = dataSource.getConnection ();

// do JDBC stuff

conn.close ();

Section 8.13, “Connection Access” of the JDO Overview shows how to access a PersistenceManager's JDBC connection. Kodo also allows you to get connections directly from the PersistenceManagerFactory's DataSource.

Example 4.6. Using the PersistenceManagerFactory DataSource

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

...

KodoPersistenceManagerFactory kpmf = KodoJDOHelper.cast (pmf);
KodoConfiguration conf = kpmf.getConfiguration ();
DataSource dataSource = (DataSource) conf.getConnectionFactory ();
Connection conn = dataSource.getConnection ();

// do JDBC stuff

conn.close ();

 

Skip navigation bar   Back to Top