Spring Transaction Management

eidher - Oct 24 '20 - - Dev Community

To support Spring transaction management we need to declare a PlatformTransactionManager bean. The @Bean method should be named transactionManager. It can return a JpaTransactionManager, DataSourceTransactionManager, JmsTransactionManager, JtaTransactionManager, etc:

    @Bean
    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }
Enter fullscreen mode Exit fullscreen mode

Now, we need to declare the transactional methods, it may be applied at the class level (to all its methods) or in the interface (since Spring 5.0):

    @Transactional
    public Response transactions(Request request) {
        ...
    }   
Enter fullscreen mode Exit fullscreen mode

Finally, we need to add an annotation to instruct the container to look for the @Transactional annotation:

@Configuration
@EnableTransactionManagement
public class AppConfig { ... }
Enter fullscreen mode Exit fullscreen mode

Spring creates proxies for all the classes annotated with @Transactional (using around advice - see Spring AOP). The proxy implements the following behavior:

  • Transaction started before entering the method
  • Commit at the end of the method
  • Rollback if the method throws a RuntimeException
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player