3.5.3. Runtime Access to DataSource
The JPA standard defines how to access JDBC connections from enterprise beans.
OpenJPA also provides APIs to retrieve a connection directly from the EntityManagerFactory's DataSource.
The EntityManager.unwrap(java.sql.Connection.class) 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.
import java.sql.Connection;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
...
EntityManager em = emf.createEntityManager();
Connection conn = (Connection) em.unwrap(java.sql.Connection.class);
// 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.
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();