0
我想先將數據實體從數據庫中提取出來,進行一些修改,並在休眠狀態下再次將其恢復到數據庫。數據庫是Mysql。我應該在更新之前提交查詢事務嗎?
我可以用下面的代碼片段做到這一點:
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();
}
}
正如你所看到的,我做了更新過程爲:
- 做一個查詢與交易。
- 開始另一項交易並在新交易中進行更新。
現在的問題是是否真正需要的第一筆交易?(帶有評論)
應該注意的是,這一計劃可能的情況下內運行的其他應用也可以提供相同的項目。即,我應該確保數據項應該在數據項上操作之前從數據庫中檢索,而不是從緩存中檢索。