armnotstrong
armnotstrong

Reputation: 9065

Should I commit the transaction for a query before update?

I want to first pull data Entity out from the db, make some modification and persist it back to the db again with hibernate. The database is Mysql.

I could do this with following code snippet:

public boolean updateStockQuantity(long quantityId, long quantity){
    Session session = HBSession.getSession();
    Transaction tx = session.beginTransacton();
    StockEntity stock = session.get(StockEntity.class, quantityId);
    tx.commit();   // <- Is this commit() really needed to prevent 
                   // a dirt update while other apps may also try to update this entity?
    stock.setQuantity(quantity);
    Transaction tx1 = session.beginTransaction();
    session.save(stock);
    try{
       tx1.commit();
       return true;
    }catch(Exception e){
       e.printExceptionStack();
       tx1.rollback();
       return false;
    }finnaly{
       session.close();
    }
}

As you can see, I do the update procedure as:

  1. Do a query with transaction.
  2. Begin another transaction and do the update in the new transaction.

Now my question is Does the first transaction really needed?(The one with comment)

Should be noted that this program may run within the circumstance that other application may also contribute to the same item. ie, I should be sure that the data Item should be retrieved from the database instead of from a cache before operating on it.

Upvotes: 0

Views: 504

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

No. That is completely useless. All you need is

Session session = HBSession.getSession();
Transaction tx = session.beginTransacton();
try {
    StockEntity stock = session.get(StockEntity.class, quantityId);
    stock.setQuantity(quantity);
    tx.commit();
    return true;
}
catch(Exception e) {
   tx.rollback();
   return false;
} finally {
   session.close();
}

Neither your code, not mine, will prevent two collections to read then update the same entity concurrently. The last transaction to update will have its changes persisted. If you want to prevent that, then use optimistic locking (i.e. a @Version annotated field).

Upvotes: 1

Related Questions