How to set the default @Transactional timeout globally
Asked Answered
C

2

5

I've a number of controllers with a lot of methods that deal with transactions... and I want to set transaction timeout to 60 for all of them:

@AllArgsConstructor
@Controller
public class MyController {

    @Transactional(timeout = 60)
    public void myMethod1(...) {
    }

    @Transactional(timeout = 60)
    public void myMethod2(...) {
    }

    ...
}

How do I set the default timeout to 60 globally so that I no longer need to specify timeout = 60 for each method?

Copious answered 11/1, 2022 at 9:38 Comment(0)
I
3

You can set the default timeout by configuring the bean of the transaction management :

@Bean
   public PlatformTransactionManager transactionManager(){
      JpaTransactionManager transactionManager
        = new JpaTransactionManager();
      transactionManager.setDefaultTimeout(10);
      transactionManager.setEntityManagerFactory(
        entityManagerFactoryBean().getObject() );
      return transactionManager;
   }

here an url that shows how to configure transaction manager for the annotation Transactional : https://www.baeldung.com/transaction-configuration-with-jpa-and-spring

Isbell answered 11/1, 2022 at 9:44 Comment(1)
I would suggest using a BeanPostProcessor to set the property, so that one can rely on the auto-configuration of Spring Boot to construct the proper tx-manager.Wring
C
9

You can use property: spring.transaction.default-timeout= # Default transaction timeout in seconds.

Conall answered 17/6, 2022 at 13:3 Comment(1)
Spring documentation supporting this answer: docs.spring.io/spring-boot/docs/2.7.7/reference/html/…Literalminded
I
3

You can set the default timeout by configuring the bean of the transaction management :

@Bean
   public PlatformTransactionManager transactionManager(){
      JpaTransactionManager transactionManager
        = new JpaTransactionManager();
      transactionManager.setDefaultTimeout(10);
      transactionManager.setEntityManagerFactory(
        entityManagerFactoryBean().getObject() );
      return transactionManager;
   }

here an url that shows how to configure transaction manager for the annotation Transactional : https://www.baeldung.com/transaction-configuration-with-jpa-and-spring

Isbell answered 11/1, 2022 at 9:44 Comment(1)
I would suggest using a BeanPostProcessor to set the property, so that one can rely on the auto-configuration of Spring Boot to construct the proper tx-manager.Wring

© 2022 - 2024 — McMap. All rights reserved.