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:
course_status = "pending"
, drivers get notified. course_status: "taken"
. course_status: "ready"
. course_status : "started"
. course_status : "arrived"
. 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.