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
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.
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.
The JDBC 3.0 API specifies a ConnectionEvent class and the following interfaces as the hooks for any connection pooling implementation: ConnectionPoolDataSource. PooledConnection. ConnectionEventListener.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With