Search code examples
javajpaejbpersistence

EntityManager JDBC connection usage


@PersistenceContext(unitName = "myPU")
private EntityManager em;

    public void run1()
    {
       // uses em
    }
    public void run2()
    {
       // uses em
    }

As per my understanding each of the methods represent different transactions.
I'm having hard times figuring out what the equivalent
code using plain JDBC could be,especially when it comes to JDBC connection usage.

Is commit issued at the end of each method ?
Is a new connection created and closed for each method ?
What does it mean that the implemenation could use a connection pool ?


Solution

  • As in most cases: It depends.

    In your case, if the methods are being invoked in different transactions, you'd get an EntityManager per bean.

    Usually the acquisition of an SQL connection is lazy. So when an EntityManager requires a connection the first time, it will fetch one from the pool you configured. The container then makes sure that the connection is unavailable to other transactions. When the transaction finishes, transactional operations such as commit or rollback are managed by the container, too.

    Is commit issued at the end of each method ?

    No, at the end of each transaction. If your methods starts new transactions, then yes.

    Is a new connection created and closed for each method ?

    The same here. If a transaction is in progress and a connection from the same pool has been used before, then it will be reused. Otherwise you wouldn't see your own changes in some other operations. If your methods start new transactions, then yes, you'd get new connections (usually just new wrapper instances around pooled connections to reduce connect/disconnect overheads) and they'd be released at the end of the transaction no matter the outcome.

    What does it mean that the implemenation could use a connection pool ?

    I think I don't completely understand your question.

    Depending on your container, you usually deal with connection pools anyway. So does the EntityManager in your case.

    Connection pooling is a way of reusing the same physical connections over and over again to, as mentioned earlier, reduce connect/disconnect overheads.

    Please let me know, if something is still unclear.