user2691659
user2691659

Reputation:

Why Sleep Solves "No Transaction is currently active" JPA

I have a web service method that uses EclipseLink JPA. This method basically inserts data into the database. Something like :

public void insert(parameters....)
   {
        em.getTransaction().begin();
        em.persist(employee);
        em.getTransaction().commit();
       // em.close();
   }

Now at the client end, i have a loop that performs inserts per iteration :

for(......) 
{ 
    websrvice.insert(parameters...)
}

After the first iteration, i get a "No transaction is currently active" exception.

Then i thought of putting a Thread.sleep(2000) after each iteration which solves the problem.

So intuitively, this could be because another transaction is trying to commit before the latter is completed which causes the error. But then again i think, why would the second insert even start when the first isn't completed ? confused.

Upvotes: 1

Views: 2090

Answers (1)

JamesB
JamesB

Reputation: 7894

You shouldnt close the entity manager at the end of your transaction.

Remove this line:

em.close();

http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#close()

"Close an application-managed entity manager. After the close method has been invoked, all methods on theEntityManager instance and anyQuery and TypedQuery objects obtained from it will throw the IllegalStateException except forgetProperties, getTransaction,and isOpen (which will return false)"

Edit:

Try using the transaction returned by the first getTransaction call, rather than invoking this method twice:

EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.persist(employee); 
transaction.commit();

Upvotes: 1

Related Questions