3.  Runtime Access to DataSource

The JPA standard defines how to access JDBC connections from enterprise beans. OpenJPA 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. OpenJPA 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 kem = OpenJPAPersistence.cast(em);
Connection conn = (Connection) kem.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 org.apache.openjpa.conf.*;
import org.apache.openjpa.persistence.*;

...

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

// do JDBC stuff

conn.close();