简体   繁体   中英

Single or Multiple Entity managers

I'm working on a RESTful API for Customer Transportation management (as a backend for an Android app).

I'm using Jax-RS with Jersey , JPA2 with EclipseLink and one single MySQL database.

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.
  2. A Driver accepts it, course_status: "taken" .
  3. The drivers arrives, course_status: "ready" .
  4. The Customer gets into the car, course_status : "started" .
  5. They arrive at destination, course_status : "arrived" .
  6. The Customer pays the driver, course_status : "paid" .

My question is: how to handle the Entity Manager instantiation ? 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

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

In this case you get your EntityManager like this

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. On the contrary EntityManager is not thread safe and each thread should get its own instance of EntityManager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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