0

I have a service, that only reads data from PostgreSQL DB (from replica, not master DB). In it's methods it can make several queries to DB. The classes and methods doesn't annotated by @Transactional. I thought that reading data from DB requires transactions too, that's why we put annotation @Transactional(readonly = true). Was I wrong? Stack: Java, Spring Boot 3

1
  • 1
    Yes you need a transaction and there will always be a transaction (on the db level), so you better control it. It might even speed things up as you will re-use the same connection to the db instead of acquiring a new one each time. Commented Feb 9, 2024 at 7:46

1 Answer 1

0

Some databases do not need a transaction to read data. Often they internally create a transaction for every query but wont tell you about that.

But reading in a transaction can give different results than reading WITHOUT a transaction.

Because: A transaction can have a locking. If your readonly-select-transaction "X" is optimistic-locking it might give changes that respect foregin insert-transactions "Y,Z" that reached savepoints and the readonly-transaction "X" assume optimisticly that "Y" an "Z" will finish successfully.

In this case the Select-Query in readonly-Transaction "X" gives results from insert-transaction "Y" and "Z" too but the same Select-Query without transactions will not contains the contributions of insert-transaction "Y" and "Z".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.