Do we need to close EntityManager resources on a select call

前端 未结 4 572
刺人心
刺人心 2021-01-26 06:42
  1. Select call leaking connections
EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"foo\");
EntityManager em = emf.crea         


        
4条回答
  •  悲&欢浪女
    2021-01-26 07:25

    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.)

提交回复
热议问题