首先看看下面的代碼,我有三個主要模型來管理StoreHouse
和StoreHouseInvetory
的和其他模型命名爲StoreHouseInventoryLock
臨時鎖定/解鎖一些金額StoreHouseInvetory
的其他進程要使用這些模型:使用session.save保存對象時,Hibernate不刷新會話?
public class StoreHouse {
private String name;
private Double currentAmount;
}
public class StoreHouseInventory {
private StoreHouse storeHouse;
private Good good;
private Double amount;
}
public class StoreHouseInventoryLock {
private StoreHouseInventory inventory;
private Double amount;
}
@Service
public class PermitService implements IPermitService {
@Autowired
private IStoreHouseInventoryLockService storeHouseInventoryLockService;
@Autowired
private IStoreHouseService storeHouseService;
@Override
@Transactional
public void addDetailToPermitFromStoreHouseInventory(long permitId, long storeHouseId, long inventoryId, double amount) {
// do some business logic here
/* save is simple method
* and uses Session.save(object)
*/
storeHouseInventoryLockService.add(inventoryId, +amount);
// do some business logic here
storeHouseService.syncCurrentInventory(storeHouseId);
}
}
@Service
public class StoreHouseService implements IStoreHouseService {
@Autowired
private IStoreHouseInventoryService storeHouseInventoryService;
@Autowired
private IStoreHouseInventoryLockService storeHouseInventoryLockService;
@Transactional
public void syncCurrentInventory(storeHouseId) {
/* is a simeple method that use query like below
* select sum(e.amount)
* from StoreHouseInventory
* where e.storeHouse.id = :storeHouseId
*/
Double sumOfInventory = storeHouseInventoryService.sumOfInventory(storeHouseId);
/* is a simeple method that use query like below
* select sum(e.amount)
* from StoreHouseInventoryLock
* where e.storeHouseInventory.storeHouse.id = :storeHouseId
*/
Double sumOfLock = storeHouseInventoryService.sumOfLock(storeHouseId);
// load method is a simple method to load object by it's id
// and used from Session.get(String entityName, Serializable id)
StoreHouse storeHouse = this.load(storeHouseId);
storeHouse.setCurrentAmount(sumOfInventory - sumOfLock);
this.save(storeHouse);
}
}
的問題是,當storeHouseInventoryService.sumOfLock
被稱爲StoreHouseService.syncCurrentInventory
,它不會是storeHouseInventoryLockService.add
方法的認識變化PermitService.addDetailToPermitFromStoreHouseInventory
方法,並錯誤地calcuates鎖的總和。
我想這是因爲會話沒有被刷新,當我打電話storeHouseInventoryLockService.add
。如果這是真的,爲什麼在這個變化期間hibernate沒有會話會話?如果不是,我該怎麼辦?
對於初學者來說,你的代碼是有缺陷的,你不應該發現異常併吞下,你的代碼會打破適當的tx管理。數據在相同的事務中可見,並且hibernate在調度數據庫時自動刷新掛起的更改。如果這沒有發生,你可能會在冬眠的背後做些事情。添加同步方法(和相關對象)的代碼。 –
對不起,這是我的錯,我刪除了'try,catch'塊 –