问题
I need to implement an MVC web service. I selected Spring MVC/Data JPA for this purpose So my service need to:
- Load some entities
- Make some business logic on it
- Update the entities and store it
- All above need to be in atomic manner
Some code snippet to clarify:
@Service
public class AService {
@Autowired
private Repository1 repository1;
@Autowired
private Repository2 repository2;
@Autowired
private Repository3 repository3;
@Transactional
public Result getResult(Long id) {
Entity1 e1 = repository1.findById(id);
Entity2 e2 = repository2.findById(id);
Entity3 e3 = repository3.findById(id);
e1.setField(doSomeLogic(...)));
e2.setField(doSomeLogic(...)));
e3.setField(doSomeLogic(...)));
repository1.save(e1);
repository2.save(e2);
repository3.save(e3);
return Result.combine(e1,e2,e3);
}
}
I guess ACID is guaranteed here (depends on isolation level?).
How about lock rows which Entities 1-3 represent for the method execution time? Is it possible some other transaction update rows which Entities 1-3 represent while doSomeLogic(...) works? How to improve it?
回答1:
What data is locked by
@Transactional
annotation?
None. @Transactional
in combination of the proper transaction support setup just starts/joins a transaction and commits it or rolls it back at the end of a method call.
Locking is done by the JPA implementation and the database.
What you normally want to use is optimistic locking.
To enable it all you have to do is add a numeric attribute with the @Version
annotation to all your entities.
This will make a transaction fail when another transaction changed the data written after it was read.
If you actually want to block the operation you need to look into pessimistic locks. You can make operations in Spring Data JPA acquire pessimistic locks by adding a @Lock annotation to the repository method.
来源:https://stackoverflow.com/questions/58827447/what-data-is-locked-by-transactional-annotation