保持JPA EntityManager打开? [英] Keeping JPA EntityManager open?

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

问题描述

我正在学习JPA,示例中的一般模式似乎如下:

I am learning JPA and the general pattern in examples seems to be as follows:

EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
// ....
em.getTransaction().commit();
em.close();

现在我想知道为什么我们不断创建和关闭EntityManagers,而不是保持开放和公正开始新的交易?保持开放与关闭它的好处和成本是什么?

Now I am wondering why do we continually create and close EntityManagers, as opposed to keeping it open and just starting new transactions? What are the benefits and costs of keeping it open vs closing it all the time?

推荐答案

两个特定于JPA的原因浮现在脑海中:

Two JPA-specific reasons come to mind:


  1. 不保证EntityManager不受JPA规范的线程保护。因此,便携式JPA应用程序一次只能在一个线程中使用EM。创建方法本地EM并在它超出范围之前关闭它的习惯用法鼓励堆栈限制EM引用。

  1. EntityManager is not guaranteed to be threadsafe by the JPA spec. Therefore, portable JPA apps can only use an EM in at most one thread at a time. The idiom of creating a method-local EM and closing it before it goes out of scope encourages stack confinement of EM references.

使用扩展的EM持久性上下文生命周期为其整个存在维护单个持久性上下文。这意味着实体停止在 commit()上自动分离。相反,它们必须手动分离,否则EM仍然负责跟踪它们。

An EM using the "Extended" Persistence Context Lifetime maintains a single persistence context for its entire existence. This means entities stop automatically detaching on commit(). Instead they must be manually detached, or else the EM remains responsible for tracking them.

这个问题实际上是一个JPA特定版本的旧何时汇集对象的问题。这很难,但答案可能很少。

This question is really a JPA-specific version of the old "when to pool objects" question. That's a tough one, but the answer is probably "rarely".

旧的developerWorks帖子阐述了这一点。要点:池对于昂贵的对象(如数据库连接)非常有意义。但是对于像EntityManager这样的短期,小型和快速初始化对象,汇集或其他形式的长期参考保留是很难卖的。

This old developerWorks post by Java concurrency expert Brian Goetz expounds the point. The gist: pools make great sense for costly objects, like database connections. But for short-lived, small, and quick-initializing objects like EntityManager, pooling or some other form of long-term reference retention is a hard sell.

但是,它是一般性问题,所以必然会有例外。也许应用程序很简单或单线程。然后这些关于线程安全的问题变得毫无意义。

But, it's a general question, so there are bound to be exceptions. Maybe the application is simple or singlethreaded. Then these concerns about threadsafety become moot.

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

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