EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"foo\"); EntityManager em = emf.crea
I had a similar connection leak. The root cause was that the select statement implicitly starts a transaction. That transaction is still active when EntityManager.close() is called, and for some reason that keeps the connection open.
Worse, our connection pool never reclaimed connections that were stuck in this state.
My fix was to explicitly check for an active transaction before closing any entityManager. I wrote a little helper function for this:
public static void rollbackAndClose(EntityManager mgr) {
if (mgr != null) {
EntityTransaction transaction = mgr.getTransaction();
if (transaction.isActive()) {
transaction.rollback();
}
mgr.close();
}
}
(I am used to transactions rolling back automatically when disconnecting a SQL client from Oracle or SQLServer, so the EntityManager behavior is counter-intuitive to me. Not sure if JPA dictates this behavior, or if it is specific to Hibernate or MySQL.)