简体   繁体   中英

Are entities fetched outside transaction managed or detached?

I always thought that entities fetched before a transaction (before entityManager.getTransaction().begin() ) were detached from the persistence context (while using the same entity manager to fetch entities as to handle the transaction). In fact, every time I was managing transactions, I had to explicitly merge entities that were fetched outside of it. If I didn't, updates were not reflected in the database.

But recently, I had a discussion with a colleague who experienced this situation the opposite way. He had to explicitly detach every entities fetched before transaction to avoid updating database.

The only difference between our codes is that my persistence.xml file is version 2.0 and his is version 1.0. But he is using JPA 2.1 in his code. Is that the reason for this strange behavior or is there something I'm missing here?

We both use Hibernate as implementation.

PersistenceContext may have two scopes:

  • TRANSACTIONAL-SCOPE
  • EXTENDED-SCOPE

TRANSACTIONAL-SCOPE

Occurs only when EntityManager is container-managed. In this case, current PersistenceContext is active as long as current transaction exists.

EXTENDED-SCOPE

Occurs when EntityManager is application-managed (be default) or container-managed (EntityManager needs annotation: @PersistenceContext( type=PersistenceContextType.EXTENDED) ).

Long story short: EXTENDED-SCOPE means that current PersistenceContext lives as long as your bean lives.

If and how things merge automatically into a transactional context depends on several factors. The JPA implementation in use, the persistence context scope, and also the transaction isolation in use. Without seeing the whole environment this cannot easily be answered. I would assume your application allows non transactional reads (dirty read, phantom read, non-repeatable read) and hence you are "allowed" to decide wether you want to merge. Another explanation could be some probem with your application code mixing several persistence contexts and hence requiring you to merge your entities read in one persistence context into another persitence context (the one which you started your TX on).

They will be managed. Any changes will be reflected to the DB within next flush . Transaction commits are flushed right away, along with the changes enqueued by pre-transactional actions.

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