Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a connection returned to the connection pool in a JPA application?

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

like image 453
mojoo-de Avatar asked Dec 04 '12 16:12

mojoo-de


People also ask

How do I return connection to connection pool?

You need to close() it after calling commit(). Note that if you use a connection pool in this way, close() doesn't really close the connection (like when you make a direct connection to the database), it just returns the connection to the pool.

How do I know if connection pooling is working?

There's a simple answer and one that makes more work: If you configure a connection pool and don't explicitly open a connection to your database anywhere in your code, the mere nonexistence of manual connection creation should be a clue that something in your connection pool works.

Which class gives connection from connection pool?

The JDBC 3.0 API specifies a ConnectionEvent class and the following interfaces as the hooks for any connection pooling implementation: ConnectionPoolDataSource. PooledConnection. ConnectionEventListener.

Does JPA use connection pool?

One key component of these starter dependencies is spring-boot-starter-data-jpa. This allows us to use JPA and work with production databases by using some popular JDBC connection pooling implementations, such as HikariCP and Tomcat JDBC Connection Pool.


2 Answers

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)

like image 190
DataNucleus Avatar answered Sep 17 '22 11:09

DataNucleus


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.

like image 41
James Avatar answered Sep 17 '22 11:09

James