Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...