简体   繁体   中英

EntityManager and hibernate Session

i am using hibernate JPA in my SpringMVC application. i am initializing it with this piece of code

@PersistenceContext
    protected EntityManager entityManager;

Now this entityManager is going to live for complete life of my application. hibernate's implementation of EntityManager is wraping a hibernate session. you can unwrap it if you wish to. When we are working with pure hibernate without JPA. we open the session do our work and close the session. If EntityManager is using hibernate's session behind the scenes when it is opened and when it is closed. if it keeps on a single session for whole life of application will not it be creating problems as entities are not automatically evicted? it may lead to out of memory error?

I will try to answer every question (based on my experience and expectations), but I am pretty sure it really depends on whether you work with JTA transactions or with UserTransactions (aka resource-local transactions):

If EntityManager is using hibernate's session behind the scenes when it is opened and when it is closed?

For every instantion of an EntityManager, a new hibernate session is opened. If you work with JTA transactions, the entityManager is closed when the transaction is closed (when your first service bean method returns).

If it keeps on a single session for whole life of application will not it be creating problems as entities are not automatically evicted? it may lead to out of memory error?

It does not keep a single hibernate session. If you configured so, it will has a pool of reusable connection, but for every new created bean it will generate a new entity manager with a new Hibernate session behind it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM