I have created hibernate application using EntityManager and Annotations based API. I am adding record in database, so its working fine. But, when i tried to send 5-6 request at same time then i am getting some exception.
My Code is :
public class Transaction {
public boolean createEntity(Object object){
EntityManager entityManager = null;
EntityTransaction transaction = null;
boolean isCreated = false;
try {
System.out.println("Persist Entity...");
entityManager = JPAEntityManagerFactory.getEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
isCreated = true;
} catch (Exception e) {
System.out.println("Exception in createEntity : " + e.getMessage());
// if anything go wrong then perform rollback
if (entityManager.getTransaction().isActive())
entityManager.getTransaction().rollback();
isCreated = false;
}finally{
transaction = null;
entityManager.close();
entityManager = null;
System.out.println("Entity Persisted....");
}
return isCreated;
}
}
So, when more than one request is trying to persist object then its giving exception.
"Transaction already active"
I debug the application. When two requests are trying to access same function at same time, and one request reaches at the end of function and another request is in the middle of function then its giving me exception.
So, My query is :
1. In above function if i check transaction.isActive(), If it is not active then do transaction.begin(). Then above error will be resolved. so, is that appropriate way to handle multiple request, all will use same database connection ?
2. Do i need to close entityManager in finally block ?
3. Do i need to explictly write transaction.commit() ?
|