I'm using Spring JdbcTemplate without Hibernate. Should I annotate method with @Transactional
if it does one simple select or one simple insert queries? And should I use @Transactional(readonly=true)
for read-only methods specifically on Oracle? What are the pros and cons of that?
Asked
Active
Viewed 5,944 times
2

anton
- 675
- 6
- 16
2 Answers
7
Should I annotate method with @Transactional if it does one simple select or one simple insert queries?
Yes. Basically, every access to the database should be done in a transaction. that's what guarantees the ACID properties. Even if you have a single query now, what makes you think tomorrow, the requirements or design won't change, and you won't have two queries? Why would you avoid using transactional?
Should I use @Transactional(readonly=true) for read-only methods specifically on Oracle?
AFAIK, with JdbcTemplate, it doesn't have any value (other than documenting that the transaction is supposed to be readonly), since you're in complete control of which queries are executed.

JB Nizet
- 678,734
- 91
- 1,224
- 1,255
3
- There is no need in
@Transactional
when you doing one simple select. But when you writing an atomic piece of logic that modifies data then you should use@Transactional
with JdbcTemplate for correct rollback in case of any exceptions. And note @JBNizet answer about ACID. @Transactional(readonly=true)
can be used as a marker or hint for underlaying low-level code, specifying that all statements can be executed on readonly data. For example, you can use it for distributing queries between master(read-write) and slave(read only) db's with RoutingDataSource.

keddok
- 531
- 1
- 5
- 15
-
31. This is plain wrong. The I in ACID means isolation. You have no guarantee at all that two subsequent selects will be done on a consistent snapshot, if you don't do them in a single transaction. So you lose the repeatable reads, or the read committed, or whatever guarantees that the isolation level provide – JB Nizet Sep 07 '17 at 10:21
-
1@JBNizet, you're completely right about transaction isolation. But topic starter asked about "one simple select" not two, and there is no need for `@Transactional`. Edited answer. – keddok Sep 07 '17 at 11:17
-
Sure, but what's the point of not using it. All you gain is the risk of forgetting to add it when you add a second query to the business logic. – JB Nizet Sep 07 '17 at 11:46
-
E.g.: spring wraps transactional method calls with couple of aop-proxies and without transactional annotation he doesn't. And sometimes this little overhead can be more important than the risk of future changes. – keddok Sep 07 '17 at 11:58