DEV Community 👩‍💻👨‍💻

eidher
eidher

Posted on

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

Top comments (1)

Collapse
 
amineamami profile image
amineamami

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

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠