Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid using the annotation @Transactional when the transaction only reads data?

I've migrated from old style of transaction management with TransactionProxyFactoryBean to a Declarative transaction management recommended by Spring to avoid exceptions with transactions that appear from time to time.

For transactions save update delete I added the annotation:

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)

It works good for me.

The question is:

Should I avoid using the annotation @Transactional when the transaction only reads data?

Example:

public TradeData getTrade(long tradeId) throws Exception {
   return em.find(TradeData.class, tradeId);
}

After reading this article, which says:

"Better yet, just avoid using the @Transactional annotation altogether when doing read operations, as shown in Listing 10:"

I'm a little confused and I don't quite understand it.

like image 468
Dylan Avatar asked Nov 07 '25 02:11

Dylan


2 Answers

For read-only operations with JDBC you don't need the @Transactional because it doesn't need a transaction, Hibernate does! So you can use @Transactional(readOnly = true). Then you are sure you don't update, delete, insert something by accident.

like image 154
Tom Jonckheere Avatar answered Nov 09 '25 19:11

Tom Jonckheere


If a particular method of your service just read information from the database yes, you can put it as read-only

    @Transactional(readOnly = true)
    public Object yourReadOnlyMethod(){}
like image 44
paul Avatar answered Nov 09 '25 18:11

paul



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!