[英]Synchronize concurrent batch updates with JPA
This example is modified and simplified, but resembles a real problem I have with legacy code that I am trying to fix.此示例经过修改和简化,但类似于我在尝试修复遗留代码时遇到的真实问题。
I have a MSSQL CAR
table (where id
is the primary key)我有一个 MSSQL
CAR
表(其中id
是主键)
id ![]() |
make![]() |
status![]() |
---|---|---|
1 ![]() |
BMW![]() |
WASHED![]() |
2 ![]() |
BMW![]() |
DIRTY![]() |
3 ![]() |
BMW![]() |
DIRTY![]() |
4 ![]() |
Ford![]() |
DIRTY![]() |
... ![]() |
... ![]() |
... ![]() |
and a /washNextCars
endpoint.和一个
/washNextCars
端点。
@PatchMapping("/washNextCars")
public ResponseEntity<List<Car>> washNextCars(
@RequestBody WashCarBody body,
@RequestParam String status,
@RequestParam String make,
@RequestParam Integer limit) {
...
}
The following request changes the state of the next 10
cars from DIRTY
to WASHED
以下请求将接下来的
10
辆车的 state 从DIRTY
更改为WASHED
PATCH /washNextCars?status=DIRTY&make=BMW&limit=10
{
"status": "WASHED"
}
This is the rough business logic:这是粗略的业务逻辑:
@Transactional
public List<Car> washNextCars(WashCarDTO dto) {
// SELECT TOP ? * FROM CAR WHERE make=? AND status='DIRTY' ORDER BY id ASC
List<Car> nextCars = carRepository.findNextCars(limit, make, status);
// do some complex validation on every car if it can be washed, therefore can't do everything in one single UPDATE query
cars.forEach(car -> {
car.setStatus("WASHED");
});
carRepository.saveAll(nextCars);
}
This endpoint works fine when called in sequence, but when called in parallel, it tries to perform the update to the same set of cars at the same time, not the next batch of cars.此端点在顺序调用时工作正常,但在并行调用时,它会尝试同时对同一组汽车执行更新,而不是下一批汽车。
Questions:问题:
@Transactional(isolation = READ_UNCOMMITED)
WASHED
before any other statement in the business logic is executed, is that correct?WASHED
,对吗?@Lock(PESSIMISTIC_WRITE_LOCK)
- Did not provide the desired effect @Lock(PESSIMISTIC_WRITE_LOCK)
- 没有提供预期的效果Try with UPDLOCK:尝试使用 UPDLOCK:
SELECT ... FROM tab1 WITH (UPDLOCK) WHERE ...
Something similar to类似于
SELECT FOR UPDATE
SELECT 更新
in Oracle.在 Oracle。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.