What data is locked by @Transactional annotation?

匆匆过客 提交于 2020-01-26 04:00:29

问题


I need to implement an MVC web service. I selected Spring MVC/Data JPA for this purpose So my service need to:

  1. Load some entities
  2. Make some business logic on it
  3. Update the entities and store it
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!