同步对JPA EntityManager的访问 [英] Synchronize access to JPA EntityManager

查看:104
本文介绍了同步对JPA EntityManager的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring,Hibernate和JPA Entity Manager。当同时获取UI的不同区域(通过jquery / ajax)时,我想同步对JPA实体管理器的访问,否则会导致对共享异常的共享引用。我如何实现这一目标?我有一个控制器,调用后端的服务方法,负责调用entitymanager上的get / save等。




  • 实体管理器: entityManager.lock(entity,LockModeType.OPTIMISTIC) ;

  • 查询: query.setLockMode(LockModeType.OPTIMISTIC);

  • NamedQuery:lockMode元素


锁定模式 OPTIMISTIC READ & OPTIMISTIC_FORCE_INCREMENT 写入






编辑:从文档


如果事务T1调用LockModeType类型的锁定。 OPTIMISTIC对
a版本化对象,实体管理器必须确保
以下现象都不会发生:


  • < P1>(脏读):事务T1修改一行。另一个事务T2然后读取该行并获取修改后的值,然后T1将
    提交或回滚。事务T2最终成功地提交
    ; T1是否提交或回滚以及
    是否在T2提交之前或之后执行都是无关紧要的。

  • P2(不可重复读取) :事务T1读取一行。在T1有
    提交之前,另一个事务T2会修改或删除该行。这两个事务最终成功提交。



锁定模式必须始终阻止现象P1和P2。

I am using Spring, Hibernate and JPA Entity Manager. When fetching different regions of the UI concurrently (via jquery/ajax) , I would like to synchronise access to JPA Entity Manager, as otherwise it results in shared references to collections exception. How do I achieve this ? I have a controller that calls service methods in the backend which are responsible for calling get/save etc on entitymanager.

解决方案

You can apply lock on the object with specific mode.

  • Entity Manager : entityManager.lock(entity, LockModeType.OPTIMISTIC);
  • Query : query.setLockMode(LockModeType.OPTIMISTIC);
  • NamedQuery : lockMode element

Lock mode OPTIMISTIC is synonymous to READ & OPTIMISTIC_FORCE_INCREMENT to WRITE.


Edit : From Documentation

If transaction T1 calls for a lock of type LockModeType.OPTIMISTIC on a versioned object, the entity manager must ensure that neither of the following phenomena can occur:

  • P1 (Dirty read): Transaction T1 modifies a row. Another transaction T2 then reads that row and obtains the modified value, before T1 has committed or rolled back. Transaction T2 eventually commits successfully; it does not matter whether T1 commits or rolls back and whether it does so before or after T2 commits.

  • P2 (Non-repeatable read): Transaction T1 reads a row. Another transaction T2 then modifies or deletes that row, before T1 has committed. Both transactions eventually commit successfully.

Lock modes must always prevent the phenomena P1 and P2.

这篇关于同步对JPA EntityManager的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆