我应该多久创建一个EntityManager? [英] How frequently should I create an EntityManager?

查看:113
本文介绍了我应该多久创建一个EntityManager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 EntityManagerFactory ,我可以为其创建一个(或多个) EntityManager 实例。我正在使用Servlet环境,并且我有一个EntityManagerFactory连接到servlet(通过servlet上下文),它在servlet的生命周期内共享(因此,对于所有用户)。

I have an EntityManagerFactory for which I can create one (or multiple) EntityManager instances. I'm using a Servlet environment, and I've got one EntityManagerFactory wired up to the servlet (via the servlet context) which is shared for the lifetime of the servlet (and therefore, for all users).

我可以执行以下操作之一:

I can do one of the following:


  • 为我的servlet的生命周期创建一个EntityManager(例如,在所有用户之间共享)

  • 为每个用户创建一个(因此每个用户在HttpSession中获得自己的用户)

  • 为每个HTTP请求创建一个(比如说) ,通过实例化一个新的并在 doGet 方法结束时将其关闭)

  • Create a single EntityManager for the lifetime of my servlet (e.g. shared between all users)
  • Create one per user (so each user gets their own in the HttpSession)
  • Create one per HTTP request (say, by instantiating a new one and closing it at the end of a doGet method)

哪个最合适?创建EntityManager的成本是否显着?
如果我做一个共享的EntityManager,是否有一个事务范围(即独立用户之间的更新可以提交其他更改)?

Which is most appropriate? Is the cost of creating an EntityManager significant? If I do a single shared EntityManager, is there a single transaction scope (i.e. updates between independent users could commit others changes)?

推荐答案

整个servlet的一个EM听起来不太好。如果你没有使用容器管理的EM(例如EJB3),那么推荐是使用EM来特定的工作单元

One EM for the whole servlet doesn't sound good. If you're not using container-managed EM's (for example EJB3) then the recommentation is to use an EM for a particular unit of work.

在Web应用程序上下文中,您的第三个建议(每个HTTP请求一个)发出声音好。但是,这可能会导致您陷入陷阱,您将服务层与数据库层绑在一起(您的服务层甚至不应该知道EM的存在)。

In a web application context your third suggestion (one per HTTP request) sounds good. However this may lead you down a pitfall where you are tying your service layer with your db layer (your service layer shouldn't even be aware of the existance of an EM).

另一种方法是以编程方式对DAO中的事务进行demark,并让DAO为每个方法调用使用新的EM。

Another approach would be to programatically demark transactions in your DAO and get your DAO to use a new EM for for every method call.

编辑:EMs创建起来很便宜而不是具有重要开销的EMF。使用一个EMF(看起来你可以)和许多EM是可行的。

EMs are cheap to create as opposed to EMFs which have a significant overhead. Using one EMF (which it appears that you do) and lots of EMs is the way to go.

这篇关于我应该多久创建一个EntityManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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