spring-framework / org.springframework.orm.jpa / JpaDialect / getJdbcConnection

getJdbcConnection

@Nullable abstract fun getJdbcConnection(entityManager: EntityManager, readOnly: Boolean): ConnectionHandle

Retrieve the JDBC Connection that the given JPA EntityManager uses underneath, if accessing a relational database. This method will just get invoked if actually needing access to the underlying JDBC Connection, usually within an active JPA transaction (for example, by JpaTransactionManager). The returned handle will be passed into the releaseJdbcConnection method when not needed anymore.

This strategy is necessary as JPA does not provide a standard way to retrieve the underlying JDBC Connection (due to the fact that a JPA implementation might not work with a relational database at all).

Implementations are encouraged to return an unwrapped Connection object, i.e. the Connection as they got it from the connection pool. This makes it easier for application code to get at the underlying native JDBC Connection, like an OracleConnection, which is sometimes necessary for LOB handling etc. We assume that calling code knows how to properly handle the returned Connection object.

In a simple case where the returned Connection will be auto-closed with the EntityManager or can be released via the Connection object itself, an implementation can return a SimpleConnectionHandle that just contains the Connection. If some other object is needed in releaseJdbcConnection, an implementation should use a special handle that references that other object.

Parameters

entityManager - the current JPA EntityManager

readOnly - whether the Connection is only needed for read-only purposes

Exceptions

javax.persistence.PersistenceException - if thrown by JPA methods

java.sql.SQLException - if thrown by JDBC methods

Return
a handle for the Connection, to be passed into releaseJdbcConnection, or null if no JDBC Connection can be retrieved

See Also
#releaseJdbcConnectionorg.springframework.jdbc.datasource.ConnectionHandle#getConnectionorg.springframework.jdbc.datasource.SimpleConnectionHandleJpaTransactionManager#setDataSource