JPA 事务的工作原理 [英] How JPA transactions works

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

问题描述

每当我想保留任何实体时,都会执行以下代码.事情似乎运行良好,但我不明白它是如何工作的!

Following code gets executed whenever I want to persist any entity. Things seems to be working fine but I fail to understand how it works !

EntityManager em = getEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
em.persist( ent );
userTransaction.commit();

上面的 EntityManager 是整个应用程序共享的单个实例.开始交易后;我只是说em.persist(entity).hibernate怎么知道它属于哪个事务!

The EntityManager above is a single instance shared by whole application. After starting the transaction; I just say em.persist(entity).. How does hibernate know it belongs to which transaction !

假设我的应用程序上有 10 个并发用户,并且所有 10 个线程都在执行上述代码.因此,正在创建和提交 10 个独立的事务.但是我没有将所有 10 个不同的实体与它们各自的交易相关联;那么 JPA 是如何解决这个问题的!

Suppose there are 10 concurrent users on my application and all 10 threads executing above code. So 10 independent transactions are getting created and committed. But all 10 different entities I am not associating them with their respective transactions; so how is JPA able to work it out !

基于答案;我们有以下;我们是说每个线程都应该有一个 EntityManager 实例吗?这不会是服务器上的一个杀戮吗!我们应该汇集这些实例吗?会不会不等于再次实现某种连接池?

Based on answers; we have below; are we saying that we should have an EntityManager instance per thread ? Will that not be a kill on the server ! Should we be pooling these instances ? Will it not be equal to again implementing sort of Connection Pooling ?

推荐答案

它有效,因为你足够幸运.幸运的是,commit 和 begin 以正确的顺序调用 - 意外.

It works because you are lucky enough. Lucky enough means that commit and begin are called in right order - accidentally.

您确实使用了来自多个线程的实体管理器的单个实例.这是错误的做法,因为它不能保证是线程安全的.通过 EntityTransaction 访问资源级事务绑定到实体管理器实例,而不是线程.

You do use single instance of entity manager from multiple threads. That is wrong thing to do, because it is not guaranteed to be thread safe. Access to resource level transaction via EntityTransaction is bound to entity manager instance, not to the thread.

因此结果是您共享相同的 EntityTransaction 并幸运地将它用于多个事务.串行使用它来启动和结束多个事务是可以的,但从多个线程使用它就不行了.

So result is that you are sharing same EntityTransaction and using it luckily serially for multiple transactions. Using it serially to strart and end multiple transaction is fine, but using it from many threads is not.

在 hibernate (4.1.4) 中,引用存储到 AbstractEntityManageImpl 类中的 tx 实例字段,但这只是实现细节.

In hibernate (4.1.4) reference is stored to tx instance field in AbstractEntityManageImpl class, but that is just implementation detail.

这篇关于JPA 事务的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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