Do I have to close() every EntityManager?

后端 未结 3 1480
半阙折子戏
半阙折子戏 2020-12-22 19:53

I have just started migrating my homegrown persistence framework to JPA.

Given that the persistence frameworks hide a lot of the plumbing, I\'m interested in knowing

相关标签:
3条回答
  • 2020-12-22 20:16

    You should.

    Frameworks have no idea how you intend to use the EM, so they cannot close it (except, may be, on finalization, which is not guaranteed). Yes, not closing them would create a resource leak.

    The idea is the same as "always close java.sql.Connection" (despite some data sources have settings to close them automatically by inactivity) or "always close Hibernate session".

    Besides, if you plan to write portable code, you shouldn't rely on specific JPA provider "being smart" -- other may fail to close the EM in time.

    0 讨论(0)
  • 2020-12-22 20:29

    It depends how you obtained it.

    If you created it using EntityManagerFactory you will have to close it no matter what framework you use.

    If you obtained it using dependency injection (eg using EJB and @PersistenceContext annotation) you should not close it by hand (AFAIK it will cause RuntimeException).

    0 讨论(0)
  • 2020-12-22 20:39

    I have obtained EntityManager using @PersistenceContext annotation in my repository. I can see that after the connectionpools reaches its maxPoolSize it does not get cleaned up.

    However if I create EntityManager using EntityManagerFactory and call entitymanager.close() then connections are getting cleaned up. I am using c3p0 as connectionpool library.

    0 讨论(0)
提交回复
热议问题