Getting a JDBC connection from EclipseLink

前端 未结 2 1514
慢半拍i
慢半拍i 2021-01-04 02:54

using EclipseLink as JPA 2.0 provider, I can obtain a JDBC connection by simply calling

Connection con = entityManager.unwrap(Connection.class);
相关标签:
2条回答
  • 2021-01-04 03:38

    But I'm unsure what I'm responsible for. Do I have to close the connection after submitting my queries? Or are I'm not allowed to close the connection, because EclipseLink also uses this connection internally.

    A good and valid question. It seems that the documentation is lacking the semantics of the unwrap() calls.

    Regarding EclipseLink, according from what I got from the source:

    EclipseLink gives you a reference to the currently active connection which it uses for the currently active client session transaction. If no transaction is active, a new will be created, associated with the session and returned from the unwrap() method.

    As a result, IMHO, a commit/rollback of such a obtained Connection may lead to undefined behavior and/or exceptions. Same is true for executing DML which changed records have been previously cached by eclipselink internal caches or for which managed entities exist.
    So when using this API, especially if the underlying transaction is dirty, be careful.

    If you can refer to internal eclipselink classes, you can access eclipselink internal connection pool to get a Connection exclusively (have a look at org.eclipse.persistence.sessions.server.ServerSession.getConnectionPool(String) ).

    0 讨论(0)
  • 2021-01-04 03:44

    If you are in the context of a JPA transaction the connection will be managed by the provider (EclipseLink). If you are outside of a transaction you are responsible for managing the connection yourself.

    See the following link for additional information:

    http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager

    0 讨论(0)
提交回复
热议问题