3. Runtime Access to DataSource
Prev | Chapter 4. JDBC | Next

## 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.

Example 4.5. Using the EntityManager's Connection

    import java.sql.Connection;
    import javax.persistence.EntityManager;
    import javax.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.

Example 4.6. 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();

Prev | Up | Next
2. Using a Third-Party DataSource | Home | 4. Database Support