7

Is a connection only returned to the Connection pool in a JPA application if i call

entityManager.close();

?

Can the connection backing the entitymanger change during its lifecycle?

thanks in advance mojoo

mojoo-de
  • 501
  • 5
  • 20
  • 2
    I found this description of connection releasing strategies with Hibernate: http://docs.jboss.org/hibernate/stable/core.old/reference/en/html/transactions-connection-release.html – GlenPeterson Oct 10 '13 at 15:14

2 Answers2

5

The JPA spec doesn't define such things and its up to the implementation to manage connections. When a transaction is active you'd be safe to assume the connection is the same until commit, for obvious reasons. Once the txn ends it may be handed back, or it may be held depending on implementation (and you don't mention yours)

DataNucleus
  • 15,497
  • 3
  • 32
  • 37
2

This depends on the JPA implementation and configuration.

In EclipseLink by default a connection is only held for the duration of an active (dirty) transaction. i.e. from the first modification or lock, until the commit or rollback. For non-transactional queries a connection is acquired on demand and returned after the query execution. This allows for maximal usage of connection pooling. So, normally em.close() does nothing.

You can configure this using the "eclipselink.jdbc.exclusive-connection.mode" persistence unit property. "Always" will hold a connection for the life of the EntityManager.

You can also use different connection pools for transactions, versus non-transactional reads. This is useful with JTA, as you can use a non-JTA DataSource for reads.

James
  • 17,965
  • 11
  • 91
  • 146