Is there a way to alter the Hibernate default transaction timeout value for only one method in a Spring Boot 2 JPA Repository? I want to keep the default 30s for my application (which contains both JPA Repositories and legacy repositories using a Hibernate SessionFactory), but allow a job (EDIT: taking place in a standalone transaction) that usually takes considerably more to be run. I'm wondering whether there is a way to specify exceptional situations, like you can except Transactions from rollbacking in certain situations.
I am looking for a solution that does not require creating a different HibernateTransactionManager than I use for the other methods.
CodePudding user response:
Spring has a @Transactional
annotation which is used to mark methods (and thus scopes) that should run in a transactional context. This annotation has a timeout
attribute which can be used to override the default timeout.
Note that the timeout can only be set at transaction level and thus the timeout
attribute is only used when the annotation causes a new transaction to be started. The documentation specifically states: "Exclusively designed for use with Propagation.REQUIRED or Propagation.REQUIRES_NEW since it only applies to newly startedtransactions."
Propagation.REQUIRED
would only cause a new transaction to be started when there's not already an active one so if you want to make sure the timeout is set, you need to start a new transaction and thus best use Propagation.REQUIRES_NEW
.
The annotation would thus be: @Transactional(timeout = 30, propagation = Propagation.REQUIRES_NEW)