问题描述
假设我想合并一个分离的实体。
当我这么做时
Let's say I would like to merge a detached entity.when I do
T mergedEntity = entityManager.merge(detachedEntity);
entityManager将从数据库加载一个实体(与detachedEntity具有相同的标识符)并复制所有数据从detachedEntity到新加载的实体。稍后我的事务结束时,该实体将被保存到数据库中。
the entityManager will load an entity (with same identifier with the detachedEntity) from database and copy all the data from the detachedEntity to the new loaded entity. When later my transaction ends, this entity will be saved to the database.
但是,在并发场景中,数据库中的实体可以通过其他事务更新。实体首先在我的事务中加载,然后在我的事务结束时刷新。
在这种情况下,我想知道是否会抛出OptimisticLockException?如果是这样,为什么合并API没有在Java doc中指定OptimisticLockException?
However, in a concurrent scenario, the entity in the database can be updated by other transactions between the entity is firstly loaded in my transaction and then flushed at the end of my transaction.In this case, I would like to know whether an OptimisticLockException will be thrown? If so, why the merge API doesn't specify the OptimisticLockException in Java doc?http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#merge(T)
谢谢
推荐答案
因为 merge()
方法不会引发此异常。当内存中的实体状态将刷新到数据库时,将抛出此异常。当调用 merge()
时,或者在显式调用 flush()
时,或者之前不会发生这种情况提交,或在执行查询之前。
Because the merge()
method is not what will throw this exception. This exception will be thrown when the state of the entity, in memory, will be flushed to the database. That doesn't happen when merge()
is called, when flush()
is called, either explicitely, or before the commit, or before a query is executed.
这篇关于JPA EntityManager的合并方法会导致OptimisticLockException吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!