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
-
1Yes 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.M. Deinum– M. Deinum2024-02-09 07:46:16 +00:00Commented Feb 9, 2024 at 7:46
1 Answer
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".