Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use @Transactional for simple queries with JdbcTemplate? [duplicate]

I'm using Spring JdbcTemplate without Hibernate. Should I annotate method with @Transactionalif 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?

like image 714
anton Avatar asked Jan 01 '26 15:01

anton


2 Answers

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.

like image 94
JB Nizet Avatar answered Jan 03 '26 06:01

JB Nizet


  1. 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.
  2. @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.
like image 44
keddok Avatar answered Jan 03 '26 05:01

keddok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!