关于线程安全和JPA EntityManager [英] Regarding Thread safety and JPA EntityManager

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

问题描述

假设我们有两个相互依赖的实体,并且每个实体都有DAO

Suppose we have two entities dependant to each other and DAOs for each of them

Entity1 -> * Entity2
Entity2 

现在假设我们有两个线程正在从数据库中提取一些数据,Thread1要求Entity1Dao获取一些初始化了相关字段的对象,同时Thread2尝试使用Entity2Dao获取相同的Entity2对象(已经检索到).

now suppose we have two threads that are pulling some data from database, Thread1 asks Entity1Dao to get some object with dependant fields initialized, meanwhile Thread2 tries to get same Entity2 objects (already retrieved) with Entity2Dao.

Entity1Dao创建EntityManager(em1)并检索数据,而Entity2Dao将创建不同的EntityManager(em2)以从数据库中获取查询对象.

Entity1Dao creates EntityManager (em1) and retrieves data, and Entity2Dao will create different EntityManager (em2) to get queries objects from database.

问题:em2是否保持锁定,直到em1关闭?如果不是,我们是否应该在其他包含所请求对象的entitymanager"上获得例外?

QUESTION: Does em2 stay locked until em1 get closed? if not should we get exception on "other entitymanager containing requested object"?

推荐答案

否.每个EntityManager都将返回不同的实体实例.

No. Every EntityManager will return different instances of the entities.

然后,除非您实现乐观并发(通过向您的实体添加@Version字段),否则并发事务将有可能写入相同的行,而最后一个将获胜.

The concurrent transactions will then, potentially, write to the same rows, and the last one will win, unless you implement optimistic concurrency (by adding an @Version field to your entities).

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

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