DEV Community

eidher
eidher

Posted on • Edited on

3 2

Spring Transaction Management

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
amineamami profile image
amineamami

Simple, Short, straight to the point. my favorite kind of articles thank you.

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay