1

Iam using Spring's @Transactional annotation for my DAO classes/methods for DB operations. Hibernate ORM configured with PostgreSQL

SessionFactory is created with @Bean in configuration and retreived using @Autowired in DAO classes.

@Autowired
SessionFactory sessionFactory;

@Transactional(value = "myTransactionManager")
public int getTotalClientsInDatabase() {
    Query countTotalClientsQuery = sessionFactory.getCurrentSession()
            .getNamedQuery(DeviceInfo.COUNT_TOTAL_CLIENTS);
    return Integer.parseInt(countTotalClientsQuery.uniqueResult().toString());
}

Whenever getTotalClientsInDatabase is called, a Transaction is opened always.

I want to prevent opening of a Transaction as it is a SELECT(DDL) query.

If @Transactional is removed Exception is thrown saying sessionFactory is not synchronized.

If readOnly=true is added performance is reduced. @Transactional(value = "myTransactionManager", readOnly=true)

Is there any way to stop Session from opening a Transaction??

Gray
  • 115,027
  • 24
  • 293
  • 354
Venkatesh
  • 303
  • 1
  • 10
  • 22

1 Answers1

1

Good practice would be in your case to mark the transaction with a propagation level of SUPPORTS:

Support a current transaction, execute non-transactionally if none exists.

So if the parent method is not in a transactional context, this method will also not be, but can.

@Transactional(propagation=Propagation.SUPPORTS, value = "myTransactionManager")
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63