What about the entites what was previously find or get by an entityManager, when closing the related (same) entityManager?

StackOverflow https://stackoverflow.com/questions/21290807

質問

I am using ThreadLocal and request/entity pattern to getting entites. This way happens i close an entityManager and there is entities in the background which i edit, copy so modify, and after it i want to persist or merge it with a new entityManager. I do not know it is a legit or rightfull solution!

I found no article, question, answer about this. Maybe i am too much of awareness, but would like to know if there is some known issue, or problems when closing entityManager this way... (I think about maybe the related entities became detached after nulling, closing it)

I manage entites RESOURCE_LOCAL way.

Or? If i feel good: the entityManager is only a bridge/path to persistent context and the entityManagers can be replaceble, there is no real or strict bond between the managed entites and the entityManager (in this sense)...

役に立ちましたか?

解決

When a you close an EntityManager, all its managed entities become detached. There is nothing wrong with that. You can still work with the detached entities as java objects, but changing their properties will not affect the database (unless you reattach it). Also once an entity is detached, you can no longer follow lazy-loaded relationships that have not been initialized while the entity was still attached.

You can later reattach a detached entity to a different EntityManager by invoking the merge() method on it. For example:

// Here myEntity is managed by entityManager1.
SomeEntity myEntity = entityManager1.find(SomeEntity.class, id);

// myEntity becomes detached.
entityManager1.close();

// I can still work with the java object.
myEntity.setSomeProperty("blah");

// Here myEntity becomes managed by entityManager2.
// It basically retrieves the current entity from the DB (based on its ID),
// then apply any change that was made to it while it was detached.
myEntity = entityManager2.merge(myEntity);

// If you commit at this point, the changes made to myEntity while
// it was detached will be persisted to the DB.

To prevent a situation where changes are made "behind your back" in the database while an entity is detached (e.g. another application modifies the corresponding row), you can use a @Version field. Each time the entity is modified, its version changes. If you try to merge a detached entity and the current version retrieved from the database has a different version, it will throw a OptimisticLockException.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top