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

I moved from the old style of transaction management with TransactionProxyFactoryBean

to the declarative transaction management recommended by Spring to avoid transaction exceptions that pop up from time to time.

For transactions, save

update

delete

I added an annotation:

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

It's good for me.

The question arises:

Should you avoid using annotation @Transactional

when a 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 annotation @Transactional

when performing read operations, as shown in Listing 10:"

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

+3


source to share


2 answers


For read-only operations, JDBC

you don't need it @Transactional

, because it doesn't need a transaction, Hibernate

does! This way you can use @Transactional(readOnly = true)

. Then you are sure that you are not updating, deleting, adding something accidentally.



+5


source


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



    @Transactional(readOnly = true)
    public Object yourReadOnlyMethod(){}

      

+5


source







All Articles