Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

java - What data is locked by @Transactional annotation?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...