注入EntityManager Vs. EntityManagerFactory的 [英] Injecting EntityManager Vs. EntityManagerFactory

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

问题描述

一个很长的问题,请耐心等待。

A long question, please bear with me.

我们正在将Spring + JPA用于Web应用程序。我的团队正在讨论在 GenericDAO 中注入 EntityManagerFactory (一个基于泛型的DAO,由APPFUSE提供,我们不会因为某些原因使用 JpaDaosupport 注入 EntityManager 。我们正在使用应用程序管理持久性。

We are using Spring+JPA for a web application. My team is debating over injecting EntityManagerFactory in the GenericDAO (a DAO based on Generics something on the lines provided by APPFUSE, we do not use JpaDaosupport for some reason) over injecting an EntityManager. We are using "application managed persistence".

反对注入 EntityManagerFactory 的论点是它太重了所以不是必需的, EntityManager 可以满足我们的需求。此外,由于Spring会为每个Web请求创建一个新的DAO实例(我怀疑这一点),因此在同一个 EntityManager 实例中不存在任何并发问题。由两个线程共享。

The arguments against injecting a EntityManagerFactory is that its too heavy and so is not required, the EntityManager does what we need. Also, as Spring would create a new instance of a DAO for every web request(I doubt this) there are not going to be any concurrency issues as in the same EntityManager instance is shared by two threads.

注入EFM的论点是,它是一个很好的做法,总是很好地拥有工厂的句柄。

The argument for injecting EFM is that its a good practice over all its always good to have a handle to a factory.

我不确定哪种方法最好,有人可以赐教我吗?

I am not sure which is the best approach, can someone please enlighten me?

推荐答案

注入EntityManagerFactory与EntityManager的优点和缺点都在Spring文档中详细说明这里,我不确定我是否可以改进。

The pros and cons of injecting EntityManagerFactory vs EntityManager are all spelled out in the Spring docs here, I'm not sure if I can improve on that.

这样说,你有一些观点应该清除的问题。

Saying that, there are some points in your question that should be cleared up.


... Spring将为每个Web请求创建一个
a DAO的新实例。 。

...Spring would create a new instance of a DAO for every web request...

这不正确。如果您的DAO是一个Spring bean,那么它是一个单例,除非您通过bean定义中的 scope 属性进行配置。为每个请求实例化DAO都会很疯狂。

This is not correct. If your DAO is a Spring bean, then it's a singleton, unless you configure it otherwise via the scope attribute in the bean definition. Instantiating a DAO for every request would be crazy.


注入EMF的理由是
这是一个很好的做法
总是很好地拥有一个
工厂的处理。

The argument for injecting EMF is that its a good practice over all its always good to have a handle to a factory.

这个论点并不真正有用。一般的良好实践表明,应该向一个对象注入完成其工作所需的最少合作者。

This argument doesn't really hold water. General good practice says that an object should be injected with the minimum collaborators it needs to do its job.

这篇关于注入EntityManager Vs. EntityManagerFactory的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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