Altug
Altug

Reputation: 1743

Update database in the middle of the transaction, possible?

 
 @Transactional
 public void start() {
  ...
  ...
  int result = entityManager
                .createQuery("update Users set name=" + value + " where user.id=5").executeUpdate();
  .....

 }

Above code gives javax.persistence.TransactionRequiredException exception.

Update database in the middle of the transaction, possible ?

Any suggestions ?

Thanks.

A.

I just wonder if

Upvotes: 0

Views: 485

Answers (1)

Andreas Dolk
Andreas Dolk

Reputation: 114767

This is a runtime exception which is thrown by the persistence provider when a transaction is required but is not active. A transaction is required because the start method is annotated as transactional. To get rid of the exception, you'll have to investigate why the line is called out of a transaction context.

A database update may be possible during a (different) transaction. Depends on the tables that are locked by the active transaction and on the transaction strategy. But in this case, it looks like you need to activate a transaction before you enter the start method.


With JPA you'd do something like this:

em = emf.createEntityManager();
tx = em.getTransaction();
tx.begin();   // now a transaction is active
start();      // call your method
// call other methods...
tx.commit();  // now the update is actually done
em.close();

Note - this is close to pseudo code, exception handling is missing in this example.

Upvotes: 4

Related Questions