我有一個帶有 H2 資料庫的 Spring Boot 應用程式,并且我已經實作了一個帶有注釋的服務,以使用具有 SERIALIZABLE 隔離級別的事務。計劃是將資料集鎖定在資料庫中,以便在我的服務仍持有要更新的資料時,并發行程無法更新資料庫。
@Transactional(isolation = Isolation.SERIALIZABLE) public class MyService {
public OrderResource addContract(final Long orderId, final ContractResource contractResource) {
// fetch the contract with Spring Data JPA repository
final Contract contract = contractRepository.findById(contractId);
// to test the scenario manually I wait for 10 seconds. In this timespan I manually change the row in the database
try {
Thread.sleep(10000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
updateService.addContract(contract, contractResource);
}
}
我現在希望受影響的記錄被鎖定在資料庫中(例如通過 Hibernate 生成的陳述句,如“SELECT FOR UPDATE”),但事實并非如此。
除了“Isolation.SERIALIZABLE”之外,我還需要注意其他任何事情來實作這一點嗎?
uj5u.com熱心網友回復:
Serializable隔離級別不一定意味著獨占資料庫鎖。例如,PostgreSQL 實作了Serializable Snapshot Isolation 模式。資料庫將在提交之前檢查可能的可序列化例外。該行為類似于樂觀鎖定方法。
如果您想選擇具有排他鎖的行,您應該SELECT FOR UPDATE直接申請。如果您想堅持使用 JPA,那么您可以嘗試使用Lock查詢注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/445629.html
