简体   繁体   English

单个或多个实体管理器

[英]Single or Multiple Entity managers

I'm working on a RESTful API for Customer Transportation management (as a backend for an Android app). 我正在研究用于客户运输管理的RESTful API(作为Android应用程序的后端)。

I'm using Jax-RS with Jersey , JPA2 with EclipseLink and one single MySQL database. 我将Jax-RS与Jersey一起使用,将JPA2与EclipseLink和一个单独的MySQL数据库一起使用。

I have different workflows: the simple ones and the ones relying on entities status. 我有不同的工作流程:简单的工作流程和依赖实体状态的工作流程。

The simple ones such authentication or account creations or getting user profile data. 简单的验证或帐户创建或获取用户配置文件数据。

The others depending on the order and the states of the entities are for example: 其他取决于实体的顺序和状态的示例是:

  1. A customer creates a course with : course_status = "pending" , drivers get notified. 客户使用以下课程创建课程: course_status = "pending" ,驾驶员将收到通知。
  2. A Driver accepts it, course_status: "taken" . 驾驶员接受它, course_status: "taken"
  3. The drivers arrives, course_status: "ready" . 司机到达了, course_status: "ready"
  4. The Customer gets into the car, course_status : "started" . 客户上车, course_status : "started"
  5. They arrive at destination, course_status : "arrived" . 他们到达目的地, course_status : "arrived"
  6. The Customer pays the driver, course_status : "paid" . 客户向驾驶员支付course_status : "paid"

My question is: how to handle the Entity Manager instantiation ? 我的问题是:如何处理Entity Manager实例化? should I instantiate an entity manager for each transaction? 我应该为每笔交易实例化一个实体经理吗? Or should I use Only one instance of the Entity Manager with singleton pattern? 还是应该仅使用一个具有单例模式的实体管理器实例?

I assume that you are developing a Java SE solution or a Java EE web profile application, ie your persistence.xml lookd something like this 我假设您正在开发Java SE解决方案或Java EE Web概要文件应用程序,即您的persistence.xml看起来像这样

<persistence-unit name="puName" transaction-type="RESOURCE_LOCAL">

In this case you get your EntityManager like this 在这种情况下,您将像这样获得EntityManager

EntityManagerFactory emf = Persistence.createEntityManagerFactory;
EntityManager em = emf.createEntityManager;

You can safely store the EntityManagerFactory reference in anything that can be accessed concurrently (singleton implementing the Registry pattern, static field or anything else) because this class is thread safe. 您可以安全地将EntityManagerFactory引用存储在可以并行访问的任何内容中(单个实现注册表模式,静态字段或其他任何方式),因为此类是线程安全的。 On the contrary EntityManager is not thread safe and each thread should get its own instance of EntityManager. 相反,EntityManager不是线程安全的,每个线程都应获得自己的EntityManager实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM