I've seen few sample on internet that checks whether the transaction is currently active at the beginning of the process.
The code below which is mine get EntityManager from the factory.
I can't figure why would one need to check whether the transaction is active BEFORE it even begin() ???
Is it because some other process may be using the same EntityManager instance? (The EntityManagerFactory is singleton but EntityManager is not)
@Path("update")
@PUT
@Consumes("application/json")
public Response machineUpdate(String content) {
JSONObject jObj = null;
EntityManager em = null;
EntityTransaction txn = null;
try {
JSONObject jObj = new JSONObject(content);
em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();
//what's this line doing here???
if(em.getTransaction().isActive()) {
return HttpStatusHandler.sendConflict();
}
txn = em.getTransaction();
txn.begin();
//more process ......
}
catch(.....
I can't see any reason for a transaction check, given the code is using the JPA transaction API, there is no way for a transaction to be active given the EntityManager was just created.
If you were using a JTA managed EntityManager, then the JTA transaction could already be active. But for JTA you cannot begin a transaction using JPA Transaction, you would have the begin the transaction with JTA, or use joinTransaction() in JPA.